- 一、使用stop方法终止线程(不推荐,可能发生不可预料的结果)
- 二、使用interrupt方法中断线程
- 三、使用退出标识,使得线程正常退出,即当run方法完成后进程终止
一、使用stop方法终止线程(不推荐,可能发生不可预料的结果)
Thread.stop()二、使用interrupt方法中断线程
interrupt主要是用来打断 sleep,wait,join 的线程
这几个方法都会让线程进入阻塞状态
interrupted():判断线程是否已经中断。interrupted()方法具有清除状态的功能,即执行后具有将状态标识清除为false。
isInterrupted():判断线程是否已经中断,但是不能清除状态标识。
打断 sleep 的线程, 会清空打断状态,以 sleep 为例
private static void test1() throws InterruptedException {
Thread t1 = new Thread(()->{
sleep(1);
}, "t1");
t1.start();
sleep(0.5);
t1.interrupt();
log.debug(" 打断状态: {}", t1.isInterrupted());
}
输出
java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at java.lang.Thread.sleep(Thread.java:340) at java.util.concurrent.TimeUnit.sleep(TimeUnit.java:386) at cn.itcast.n2.util.Sleeper.sleep(Sleeper.java:8) at cn.itcast.n4.TestInterrupt.lambda$test1$3(TestInterrupt.java:59) at java.lang.Thread.run(Thread.java:745) 21:18:10.374 [main] c.TestInterrupt - 打断状态: false
打断正常运行的线程
打断正常运行的线程, 不会清空打断状态
private static void test2() throws InterruptedException {
Thread t2 = new Thread(()->{
while(true) {
Thread current = Thread.currentThread();
boolean interrupted = current.isInterrupted();
if(interrupted) {
log.debug(" 打断状态: {}", interrupted);
break;
}
}
}, "t2");
t2.start();
sleep(0.5);
t2.interrupt();
}
输出
20:57:37.964 [t2] c.TestInterrupt - 打断状态: true三、使用退出标识,使得线程正常退出,即当run方法完成后进程终止
public void run() {
while(flag){
//do something
}
}



