线程调用interrupt()方法后,在线程的run方法中判断当前对象的interrupted()状态,如果是中断状态则抛出异常,达到中断线程的效果。 如下示例:
public class MyThread extends Thread {
@Override
public void run() {
try {
for (int i = 0; i < 500000; i++) {
if (MyThread.interrupted()){
System.out.println("已经是停止状态了,我要退出了!");
throw new InterruptedException();
}
System.out.println("i = " + (i+1));
}
System.out.println("如果我被输出了,则代表线程没有停止");
} catch (InterruptedException e) {
System.out.println("在MyThread类中的run方法中被捕获");
e.printStackTrace();
}
}
}
/**
* 根据中断状态退出for循环
* @Author: xjf
* @Date: 2019/5/25 13:27
*/
public class Main {
public static void main(String[] args) {
try {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(100);
myThread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("end!");
}
}
i = 19115
i = 19116
i = 19117
i = 19118
i = 19119
end!
已经是停止状态了,我要退出了!
在MyThread类中的run方法中被捕获
java.lang.InterruptedException
at com.book.interrupt_exit.MyThread.run(MyThread.java:15)
Process finished with exit code 0
public class MyThread extends Thread {
@Override
public void run() {
try {
System.out.println("run-----------start");
Thread.sleep(5000);
System.out.println("run-----------end");
} catch (InterruptedException e) {
System.out.println("在沉睡中被停止!进入catch,线程的是否处于停止状态:" + this.isInterrupted());
e.printStackTrace();
}
}
}
public class Main {
public static void main(String[] args) {
try {
MyThread myThread = new MyThread();
myThread.start();
Thread.sleep(2000);
System.out.println("状态:"+MyThread.interrupted());
myThread.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
run-----------start
状态:false
java.lang.InterruptedException: sleep interrupted
在沉睡中被停止!进入catch,线程的是否处于停止状态:false
at java.lang.Thread.sleep(Native Method)
at com.book.sleep_interrupt.MyThread.run(MyThread.java:13)
public class MyThread1 extends Thread {
@Override
public void run() {
try {
for (int i = 0; i < 100000; i++) {
System.out.println("i = " + (i+1));
}
System.out.println("run begin");
//interrupt是做一个中断标记,当时不会去中断正在运行的线程,当该线程处于阻塞状态时就会进行中断
//因此,先进行interrupt后,再遇到sleep阻塞时,才会进行中断
Thread.sleep(200000);
System.out.println("run end");
} catch (InterruptedException e) {
System.out.println("先停止,再遇到了sleep! 进入catch!");
e.printStackTrace();
}
}
}
public class Main1 {
public static void main(String[] args) {
MyThread1 myThread1 = new MyThread1();
myThread1.start();
myThread1.interrupt();
System.out.println("end!");
}
}
i = 99993
i = 99994
i = 99995
i = 99996
i = 99997
i = 99998
i = 99999
i = 100000
run begin
先停止,再遇到了sleep! 进入catch!
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.book.sleep_interrupt.MyThread1.run(MyThread1.java:19)
线程调用stop()方法会被暴力停止,方法已弃用。该方法会有不好的后果:
备注:建议使用“抛异常”的方法来实现线程的停止,因为在catch块中还可以将异常向上抛,使线程停止的事件得以传播
参考:《Java多线程编程核心技术》