今天,在学习线程中断的过程中,学到了之前不知道的新知识。线程中断避免使用Thread提供的stop()方法。正确的方法是使用interrupt()方法,案例如下:
public class MyRunnable implements Runnable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Thread thread = new Thread(new MyRunnable());
thread.start();
//使线程休眠5秒
thread.sleep(5000);
//中断线程
//thread.stop();
thread.interrupt();
}
@Override
public void run() {
int i = 0;
//判断线程没有中断并且小于1000000的情况下,执行循环逻辑
// while(!Thread.interrupted() && i < 1000000){
while(!Thread.currentThread().isInterrupted() && i < 1000000){
System.out.println(i ++);
}
System.out.println("Thread.currentThread().isInterrupted() = " +Thread.currentThread().isInterrupted());
}
}
解释:如代码所示,启动线程5秒之后中断线程。线程执行过程中,判断线程是否被中断,如果中断退出循环。
通过上述来看,感觉Thread提供了interrupt()和isInterrupted()配合使用。在线程中断后,可以利用isInterrupted()方法,人为的来控制线程中断后,需要处理的逻辑,相比stop()中断线程方法显得很灵活。并且,java已经弃用了stop()方法,相关说明java api有解释,但我还理解不了。
注意:
1.Thread.interrupted()和Thread.currentThread().isInterrupted()方法都可以获取判断终止线程的标志。区别在于Thread.interrupted()获取线程终止状态为true后,会重置状态。Thread.currentThread().isInterrupted()获取线程终止状态为true后,不会重置。
查看源码:
//Thread.interrupted()方法调用的源码
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
//Thread.currentThread().isInterrupted()方法调用的源码
public boolean isInterrupted() {
return isInterrupted(false);
}
/**
* Tests if some Thread has been interrupted. The interrupted state
* is reset or not based on the value of ClearInterrupted that is
* passed.
* 中文解释:如果出入参数为true,那么终止状态被重置,如果为false不重置。
*/
private native boolean isInterrupted(boolean ClearInterrupted);
2.如果正在执行的线程在休眠时,线程终止,那么线程会抛java.lang.InterruptedException异常,并且线程终止状态会被重置。例子如下:
public class MyRunnable implements Runnable {
public static void main(String[] args) throws ExecutionException, InterruptedException {
Thread thread = new Thread(new MyRunnable());
thread.start();
thread.sleep(5000);
// thread.stop();
thread.interrupt();
}
@Override
public void run() {
int i = 0;
// while(!Thread.interrupted() && i < 1000000){
while(!Thread.currentThread().isInterrupted() && i < 1000000){
System.out.println(i ++);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread.currentThread().isInterrupted() = " +Thread.currentThread().isInterrupted());
}
}
执行上述代码,在while循环过程中,线程被终止。跳出循环,当前线程终止状态为true,在执行Thread.sleep(1000);这行代码时,抛出java.lang.InterruptedException异常,同时线程终止状态重置为false。