线程中断 interrupt()
线程的Thread.interrupt()方法是中断线程,将会设置该线程的中断状态位,即设置为true,中断的结果线程是死亡、还是等待新的任务或是继续运行至下一步,完全取决于目标线程的自行决定。线程会不时地检测这个中断标志位,以判断线程是否应该被中断(中断标示值是否为true)。它并不像stop方法那样会强制的终止一个正在运行的线程。
中断相关的方法
public static boolean interrupted | 测试当前线程是否已经中断。线程的中断状态 由该方法清除。换句话说,如果连续两次调用该方法,则第二次调用将返回 false。 |
---|---|
public boolean isInterrupted() | 测试线程是否已经中断。线程的中断状态 不受该方法的影响。 |
public void interrupt() | 中断线程 |
如果一个线程收到中断的信息,但是没有处理中断的逻辑,将继续之前的运行而不受任何影响。
引入sleep()方法
public static native void sleep(long millis) throws InterruptedException;
native标识的方法叫本地方法,该方法的功能是由额外的C++代码实现的,而这个C++代码其实就在电脑本地里
sleep 会抛出InterruptedException异常,在案例中,在中断线程t1.interrupt()时,会被catch (InterruptedException e) 捕获。这时需要重新设置为中断状态Thread.currentThread().interrupt()。
TimeUnit.SECONDS.sleep()
对Thread.sleep方法的包装,实现是一样的,只是多了时间单位转换和验证,然而TimeUnit枚举成员的方法却提供更好的可读性
public void sleep(long timeout) throws InterruptedException {
if (timeout > 0) {
long ms = toMillis(timeout);
int ns = excessNanos(timeout, ms);
Thread.sleep(ms, ns);
}
}
案例:
package com.Thread;
import java.util.concurrent.TimeUnit;
public class Thread_03_demo {
public static void main(String[] args) {
Thread t1 = new Thread("a"){
@Override
public void run() {
int i=0;
while(true){
if(Thread.currentThread().isInterrupted()){
System.out.println("Interrupted :"+Thread.currentThread().getName());
break;
}
System.out.println(++i);
try {
//sleep会清除interrupt标记
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Interruted When Sleep ");
Thread.currentThread().interrupt();
}
Thread.yield();
}
}
};
t1.start();
try{
//暂停三毫秒
TimeUnit.MILLISECONDS.sleep(3000);
}catch (InterruptedException e){
e.printStackTrace();
}
//线程中断
t1.interrupt();
}
}
//输出结果
1
2
3
Interruted When Sleep
Interrupted :a