
首先
一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止。
所以,Thread.stop, Thread.suspend, Thread.resume 都已经被废弃了。
其次
在Java中没有办法立即停止一条线程,然而停止线程却显得尤为重要,如取消一个耗时操作。
因此,Java 提供了一种用于停止线程的协商机制——中断。
中断只是一种协作协商机制,Java没有给中断增加任何语法,中断的过程完全需要程序员自己实现。若要中断一个线程,你需要手动调用该线程的 interrupt 方法,该方法也仅仅是将线程对象的中断标识设成true;接着你需要自己写代码不断地检测当前线程的标识位,如果为true,表示别的线程要求这条线程中断,此时究竟该做什么需要你自己写代码实现。
每个线程对象中都有一个标识,用于表示线程是否被中断;该标识位为true表示中断,为false表示未中断;
通过调用线程对象的interrupt方法将该线程的标识位设为true;可以在别的线程中调用,也可以在自己的线程中调用。
| 方法 | 描述 |
|---|---|
| public void interrupt() | 实例方法,实例方法interrupt()仅仅是设置线程的中断状态为true,发起一个协商而不会立刻停止线程 |
| public static boolean interrupted() | 静态方法,Thread.interrupted();判断线程是否被中断,并清除当前中断状态 这个方法做了两件事:1、返回当前线程的中断状态 2 、将当前线程的中断状态设为false(这个方法有点不好理解,因为连续调用两次的结果可能不一样。 |
| public boolean isInterrupted() | 实例方法,判断当前线程是否被中断(通过检查中断标志位) |
通过面试演示三个API的使用方法以及注意事项
stopstop和suspend及resume一样都是过期作废的方法。因此不推荐使用
第一种方式,使用 volatile 中断线程:
利用 volatile 的可见性,用于判断是否中断的一个标志位
public class interruptTest01 {// 标志位static volatile boolean isStop = false;public static void main(String[] args) {new Thread(() -> {while (true) {if (isStop) {System.out.println(Thread.currentThread().getName() +"\t" + "isStop 被修改为true,线程停止");break;}System.out.println("hello, volatile....");}}, "t1").start();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}new Thread(() -> {isStop = true;}, "t2").start();}
}
第二种方式:通过 AtomicBoolean 中断
static AtomicBoolean atomicBoolean = new AtomicBoolean(false);public static void main(String[] args) {new Thread(() -> {while (true) {if (atomicBoolean.get()) {System.out.println(Thread.currentThread().getName() +"\t" + "atomicBoolean 被修改为true,线程停止");break;}System.out.println("hello, atomicBoolean....");}}, "t1").start();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}new Thread(() -> {atomicBoolean.set(true);}, "t2").start();}
第三种方式:使用 Thread类 自带的 api 实现中断
public static void main(String[] args) {Thread t1 = new Thread(() -> {while (true) {if (Thread.currentThread().isInterrupted()) {System.out.println(Thread.currentThread().getName() + "\t" + "interrupted 被修改为true,线程停止");break;}System.out.println("hello, interrupted....");}}, "t1");t1.start();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}new Thread(() -> {// 设置中断标志为 truet1.interrupt();}, "t2").start();}
不是
如果线程处于正常活动状态,那么会将该线程的中断标志设置为 true,仅此而已。被设置中断标志的线程将继续正常运行,不受影响。所以, interrupt() 并不能真正的中断线程,需要被调用的线程自己进行配合才行。
中断不活动的线程不会产生任何影响,看下面案例
public class InterruptTest02 {public static void main(String[] args) {Thread t1 = new Thread(() -> {for (int i = 0; i < 100; i++) {System.out.println("----- " + i);}// true,虽然中断标志位为 true,但是并没中断线程System.out.println("第二次中断标志: " + Thread.currentThread().isInterrupted());}, "t1");t1.start();System.out.println("默认中断标志状态: " + t1.isInterrupted() ); //false// 将标志位设置为truet1.interrupt();try {Thread.sleep(2);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("第一次中断标志: " + t1.isInterrupted()); //truetry {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}// 由于线程 t1已结束,对于结束的线程,中断不会产生任何影响System.out.println("第三次中断标志: " + t1.isInterrupted()); // false}
}
输出结果:
默认的中断标志为false
当设置中断标志为 true 时,线程并没有结束,因此中断需要线程配合
当线程结束,中断不会产生任何影响
默认中断标志状态: false
----- 0
----- 1
----- 2
----- 3
----- 4
----- 5
----- 6
----- 7
----- 8
----- 9
----- 10
----- 11
----- 12
----- 13
----- 14
----- 15
----- 16
----- 17
----- 18
----- 19
----- 20
----- 21
----- 22
----- 23
----- 24
----- 25
----- 26
----- 27
----- 28
----- 29
----- 30
----- 31
----- 32
----- 33
----- 34
----- 35
----- 36
----- 37
----- 38
----- 39
----- 40
----- 41
----- 42
----- 43
----- 44
----- 45
----- 46
----- 47
----- 48
----- 49
----- 50
----- 51
----- 52
----- 53
----- 54
----- 55
----- 56
----- 57
----- 58
----- 59
----- 60
----- 61
----- 62
第一次中断标志: true
----- 63
----- 64
----- 65
----- 66
----- 67
----- 68
----- 69
----- 70
----- 71
----- 72
----- 73
----- 74
----- 75
----- 76
----- 77
----- 78
----- 79
----- 80
----- 81
----- 82
----- 83
----- 84
----- 85
----- 86
----- 87
----- 88
----- 89
----- 90
----- 91
----- 92
----- 93
----- 94
----- 95
----- 96
----- 97
----- 98
----- 99
第二次中断标志: true
第三次中断标志: falseProcess finished with exit code 0
如果线程处于被阻塞状态(例如处于sleep, wait, join 等状态),在别的线程中调用当前线程对象的interrupt方法,那么线程将立即退出被阻塞状态(中断状态将被清除),并抛出一 个InterruptedException异常。
public class InterruptTest03 {public static void main(String[] args) {Thread t1 = new Thread(() -> {while (true) {if (Thread.currentThread().isInterrupted()) {System.out.println("中断标志位被修改: " + Thread.currentThread().isInterrupted() + ",线程停止");break;}try {Thread.sleep(20);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("hello,interrupt");}}, "t1");t1.start();try {Thread.sleep(200);} catch (InterruptedException e) {e.printStackTrace();}t1.interrupt();}
}
输出结果:

从结果可以看出,当线程正处于 sleep 阻塞状态时,设置标志位为 true,会立刻打断阻塞状态,并抛出InterruptedException异常,最终要的是会导致线程处于死循环。因此想要避免死循环,需要在 catch 语句中再一次设置中断标志

演示输出结果:

Thread.interrupted() 会做俩件事请:
public class InterruptTest04 {public static void main(String[] args) {System.out.println(Thread.currentThread().getName()+ "\t" + Thread.interrupted()); // falseSystem.out.println(Thread.currentThread().getName()+ "\t" + Thread.interrupted());// false// 设置标志位为 trueThread.currentThread().interrupt();System.out.println(Thread.currentThread().getName()+ "\t" + Thread.interrupted());// trueSystem.out.println(Thread.currentThread().getName()+ "\t" + Thread.interrupted());// false}
}
isInterrupted 和 interrupted 的区别?
源码中的区别:

官方解释:用于创建锁和其他同步类的基本线程阻塞原语。

核心 API :
static void | park() 禁止当前线程进行线程调度,除非许可证可用。 |
|---|---|
static void``unpark(Thread thread) | 为给定的线程提供许可证(如果尚未提供)。 |
wait()方法让线程等待,使用Object中的notify()方法唤醒线程Condition的await()方法让线程等待,使用signal()方法唤醒线程LockSupport类可以阻塞当前线程以及唤醒指定被阻塞的线程使用 wait、notify 演示:
使用 wait、notify 时的注意点
public class WaitNotifyTest {public static void main(String[] args) {Object obj = new Object();new Thread(() -> {synchronized (obj) {System.out.println(Thread.currentThread().getName() + " come in...");try {obj.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(Thread.currentThread().getName() + " end");}, "t1").start();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}new Thread(() -> {synchronized (obj) {System.out.println(Thread.currentThread().getName() + " 唤醒t1...");// 唤醒线程obj.notify();}}, "t2").start();}
}
使用 await、signal 演示
使用时的注意事项和wait notify 一样。
public class LockSupportTest01 {public static void main(String[] args) {Lock lock = new ReentrantLock();Condition condition = lock.newCondition();new Thread(() -> {lock.lock();System.out.println(Thread.currentThread().getName() + " come in...");try {condition.await();} catch (InterruptedException e) {e.printStackTrace();} finally {lock.unlock();}System.out.println(Thread.currentThread().getName() + " end");}, "t1").start();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}new Thread(() -> {lock.lock();try {System.out.println(Thread.currentThread().getName() + " 唤醒t1...");// 唤醒线程condition.signal();} finally {lock.unlock();}}, "t2").start();}
}
以上俩种方式使用的局限性:
因此衍生出了 park/unpark
通过park()和unpark(thread)方法来实现阻塞和唤醒线程的操作。
park 相当于 wait、await 方法 用来阻塞线程, unpark 相当于 notify、signal 方法 用来唤醒线程。
而 park/ unpark 与另外俩种方式的区别:
park/ unpark 不会抛出异常,另外俩种方式会抛出 InterruptedException
park/ unpark 采用 Permit (许可证) 的方式来阻塞、唤醒线程,每个使用 LockSupport 的线程都有一个许可证
调用一次 park 方法会消耗掉一张 许可证,因此当前线程会进入阻塞状态
unpark 会为指定的线程发放一张许可证,如果线程处于阻塞状态,会将线程唤醒。无论调用多少次,只会发放一张许可证
LockSupport 和 Semaphore 不同的是,LockSupport 的许可证只有一张,无法累加。消耗完就会被阻塞。
代码演示一:
我们可以看到,park、unpark 并没在同步块中使用,LockSupport 并没有范围的局限性。
public class LockSupportTest01 {public static void main(String[] args) {Thread t1 = new Thread(() -> {System.out.println(Thread.currentThread().getName() + " come in...");// 消耗许可证LockSupport.park();System.out.println(Thread.currentThread().getName() + " end...");}, "t1");t1.start();try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}new Thread(() -> {System.out.println(Thread.currentThread().getName() + " 为 t1 发放许可证...");// 发放许可证LockSupport.unpark(t1);}, "t2").start();}
}
代码演示二:、
park、unpark 并没有执行顺序的问题,也就是先唤醒在阻塞也不会出现 IllegalMonitorStateException 异常。
public class LockSupportTest01 {public static void main(String[] args) {Thread t1 = new Thread(() -> {try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + " come in...");// 消耗许可证LockSupport.park();System.out.println(Thread.currentThread().getName() + " end...");}, "t1");t1.start();new Thread(() -> {System.out.println(Thread.currentThread().getName() + " 为 t1 发放许可证...");// 发放许可证LockSupport.unpark(t1);}, "t2").start();}
}
输出结果:

代码演示三:
演示许可证的唯一性
消耗三张许可证,而 无论调用多少次 unpark 都只会发放一张许可证。 因此许可证不够,线程进入阻塞状态
public class LockSupportTest01 {public static void main(String[] args) {Thread t1 = new Thread(() -> {try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName() + " come in...");// 消耗许可证LockSupport.park();LockSupport.park();LockSupport.park();System.out.println(Thread.currentThread().getName() + " end...");}, "t1");t1.start();new Thread(() -> {System.out.println(Thread.currentThread().getName() + " 为 t1 发放许可证...");// 发放许可证LockSupport.unpark(t1);LockSupport.unpark(t1);LockSupport.unpark(t1);}, "t2").start();}
}
结果:

各位彭于晏,如有收获点个赞不过分吧…✌✌✌

扫码关注公众号 【我不是秃神】 回复 JUC 可下载 MarkDown 笔记