转载:https://www.cnblogs.com/jenkov/p/juc_interrupt.html
进阶文章(有基础的可以看看)https://www.cnblogs.com/onlywujun/p/3565082.html
在java的api中有stop、suspend等方法可以停止一个线程,但由于这些方法在使用上存在不安全性,会带来不好的副作用,不建议被使用。
原因:https://blog.csdn.net/xingjiarong/article/details/47984659
首先明确:中断不是停止一个线程,只是改变中断状态
中断在java中主要有3个方法,interrupt(),isInterrupted()和interrupted()。
- interrupt(),在一个线程中调用另一个线程的interrupt()方法,即会向那个线程发出信号——线程中断状态已被设置。至于那个线程何去何从,由具体的代码实现决定。
- isInterrupted(),用来判断当前线程的中断状态(true or false)。
- interrupted()是个Thread的static方法,用来恢复中断状态
首先一个普通的中断线程的例子:
public class InterruptionInJava implements Runnable{
private volatile static boolean on = false;
public static void main(String[] args) throws InterruptedException {
Thread testThread = new Thread(new InterruptionInJava(),"InterruptionInJava");
//start thread
testThread.start();
Thread.sleep(1000);
InterruptionInJava.on = true;
System.out.println("main end");
}
@Override
public void run() {
while(!on){
if(Thread.currentThread().isInterrupted()){
System.out.println("Yes,I am interruted,but I am still running");
}else{
System.out.println("not yet interrupted");
}
}
}
}
运行结果:
这种开关的方式看起来包治百病,但是当遇到线程阻塞时,就会很无奈了,正如下面代码所示:
public class InterruptionInJava implements Runnable{
private volatile static boolean on = false;
public static void main(String[] args) throws InterruptedException {
Thread testThread = new Thread(new InterruptionInJava(),"InterruptionInJava");
//start thread
testThread.start();
Thread.sleep(1000);
InterruptionInJava.on = true;
System.out.println("main end");
}
@Override
public void run() {
while(!on){
try {
Thread.sleep(10000000);
} catch (InterruptedException e) {
System.out.println("caught exception: "+e);
}
}
}
}
线程被阻塞无法被中断。这时候救世主interrupt函数又回来了,它可以迅速中断被阻塞的线程,抛出一个InterruptedException,把线程从阻塞状态中解救出来,show the code。
public class InterruptionInJava implements Runnable{
private volatile static boolean on = false;
public static void main(String[] args) throws InterruptedException {
Thread testThread = new Thread(new InterruptionInJava(),"InterruptionInJava");
//start thread
testThread.start();
Thread.sleep(1000);
InterruptionInJava.on = true;
testThread.interrupt();
System.out.println("main end");
}
@Override
public void run() {
while(!on){
try {
Thread.sleep(10000000);
} catch (InterruptedException e) {
System.out.println("caught exception right now: "+e);
}
}
}
}
运行结果: