一、java Thread常见状态有:NEW=新建,RUNNABLE=运行,TERMINATED=中断,BLOCKED=阻塞,WAITING状态时会=等待,SLEEPING=休眠。
二、线程中断interrupt():
1、A线程调用B.interrupt()中断B时若B在SLEEPING或者WAITING状态时会出现InterruptedException,此时B线程跳出当前代码块并执行完剩余的代码;此时调用isInterrupted()获取B线程状态为false。
2、如需依赖中断状态处理逻辑必须在扑火InterruptedException异常并再次进行中断Thread.currentThread().interrupt();再次中断后isInterrupted()获取B线程状态为true。此时需调用return结束当前线程任务,否则余下代码仍会继续执行。
3、不管强制中断与否B线程执行完毕后,isInterrupted()重置为false。
测试代码如下:
public class ThreadTest {
public static void main(String[] args){
Thread a;
a = new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println("1"+Thread.currentThread().isInterrupted());
Thread.sleep(5000);
System.out.println("2"+Thread.currentThread().isInterrupted());
} catch (InterruptedException e) {
System.out.println("3"+Thread.currentThread().isInterrupted());
Thread.currentThread().interrupt();
System.out.println("3.5"+Thread.currentThread().isInterrupted());
e.printStackTrace();
return;
}
System.out.println("4"+Thread.currentThread().isInterrupted());
}
});
a.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
a.interrupt();
System.out.println("5"+a.isInterrupted());
try {
Thread.sleep(6000);
System.out.println("6"+a.isInterrupted());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
直接中断测试结果:
捕获异常进行中断并return: