并发编程学习目录
一、怎么中断一个正在运行的线程
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(()->{
int i = 0;
while (!Thread.currentThread().isInterrupted()) {
i++;
System.out.println(i);
}
});
t1.start();
Thread.sleep(1000);
t1.interrupt();// 中断
}
首先中断一个线程,必须要有判断中断的标识。Thread.currentThread().isInterrupted() 标识当前线程是不是中断状态。如果没有判断标识的逻辑代码,线程是不能中断的。
当调用 t1.interrupt()的时候会将中断标识的值改为true.当线程判断等于true时。线程将会中断。
二、怎么中断一个阻塞的线程
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(()->{
while (!Thread.currentThread().isInterrupted()) {
try {
Thread.sleep(1000000);
} catch (InterruptedException e) { //抛出异常,中断标志改为false(复位)
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
});
t1.start();
Thread.sleep(1000);
t1.interrupt();// 中断
}
这种情况线程并不会阻塞1000秒以后在中断。但我们调用 t1.interrupt() 的时候。jvm层面会抛出一个InterruptedException的异常。从文字上来看,就是一个中断的异常。我们捕获以后,会进行复位操作(就是中断标识改为false),这个时候我们在catch当中做处理,是继续运行,还是中断线程。
问题:为什么会进行复位操作,让我们在进行处理。而不是直接中断?
interrupt 这种中断方式,是一种友好的中断方式。当调用t1.interrupt()的时候是给线程发了一个中断的信号。而不是马上就让该线程中断。决定是否中断的权利。还是交给当前的线程。就相当于linux 中的 kill 和 kill -9.