public void interrupt();
这个方法中是在目标线程中设置了一个标志,表示它已经被中断,并立即返回。有可能interrupt()抛出一个异常SercurityException,表示发出中断请求的线程没有权限中断其他线程。在Thread上调用checkAccess()方法进行安全性检查,它又会检查SecurityManager是否已经安装,如果已经安装,则调用它的checkAccess(Thread)方法。
package com.kkoolerter.jdk.thread;
/**
* 中断休眠线程
*
* @author Jenson
*
*/
public class InterruptSleepThread implements Runnable {
public static void main(String[] args) {
InterruptSleepThread ist = new InterruptSleepThread();
Thread t = new Thread(ist);
t.start();
try {
Thread.sleep(5000);//如果当前线程休眠的时间比ist短,则将会抛出InterruptedException;
//如果大于或等于,则线程正常退出
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("in main - interrupting other thread");
t.interrupt();
System.out.println("in main - leaving");
}
@Override
public void run() {
try {
System.out.println("in run()-about to sleep for 4 secondes");
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
System.out.println("in run ()- doing stuff after nap");
System.out.println("in run() - leaving normally");
}
}