目录

void interrupt()

描述 (Description)

java.lang.Thread.interrupt()方法中断此线程。 中断不活动的线程不会产生任何影响。

声明 (Declaration)

以下是java.lang.Thread.interrupt()方法的声明

public void interrupt()

参数 (Parameters)

NA

返回值 (Return Value)

此方法不返回任何值。

异常 (Exception)

SecurityException - 如果当前线程无法修改此线程。

例子 (Example)

以下示例显示了java.lang.Thread.interrupt()方法的用法。

package com.iowiki;
import java.lang.*;
public class ThreadDemo implements Runnable {
   Thread t;
   ThreadDemo() {
      t = new Thread(this);
      System.out.println("Executing " + t.getName());
      // this will call run() fucntion
      t.start();
      // interrupt the threads
      if (!t.interrupted()) {
         t.interrupt();
      }
      // block until other threads finish
      try {  
         t.join();
      } catch(InterruptedException e) {}
   }
   public void run() {
      try {       
         while (true) {
            Thread.sleep(1000);
         }
      } catch (InterruptedException e) {
      System.out.print(t.getName() + " interrupted:");
      System.out.println(e.toString());
      }
   }
   public static void main(String args[]) {
      new ThreadDemo();
      new ThreadDemo();
   }
} 

让我们编译并运行上面的程序,这将产生以下结果 -

Executing Thread-0
Thread-0 interrupted:java.lang.InterruptedException: sleep interrupted
Executing Thread-1
Thread-1 interrupted:java.lang.InterruptedException: sleep interrupted
↑回到顶部↑
WIKI教程 @2018