线程中Interrupt方法的使用
程序中,有些线程的中断需要外部干预,比如线程中存在while(true)循环,或者存在一些阻塞操作,比如 sleep、wait、join等。
中断线程的方式,如果直接使用stop、suspend等方法,对程序来说是不太严谨的,这些方法类似于直接杀死线程,可能会造成数据问题。
interrupt方法的使用可以解决该问题,调用指定线程的该方法,表示向指定线程发起通知,可以执行中断线程的操作了,而具体什么时候执行,由线程自己决定,这种方式可以让程序处理更加严谨。
循环中断
public class InterruptDemo {
private static int i;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
while (!Thread.currentThread().isInterrupted()){
i++;
}
System.out.println("Num:" + i);
},"InterruptDemo");
thread.start();
TimeUnit.SECONDS.sleep(1);
thread.interrupt();
}
}
阻塞中断
public class InterruptDemo {
private static int i;
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
while (!Thread.currentThread().isInterrupted()){
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
Thread.currentThread().interrupt();//此处一定要再次中断
}
}
System.out.println("Num:" + i);
},"InterruptDemo");
thread.start();
TimeUnit.SECONDS.sleep(1);
thread.interrupt();
}
}
InterruptedException 的出现表示此处可能有中断操作,需要线程自行处理(业务上可以在此处进行一些数据处理,比如保存一些数据操作)