1 线程中断机制
1.1Java.lang.Thread下的三个方法
- 如何中断一个运行中的线程?
- 如何停止一个运行中的线程?
1.2 什么是中断机制
- 首先,一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止,自己来决定自己的命运,所以,Thread.stop,Thread.suspend,Thread.resume都已经被废弃了
- 其次,在Java中没有办法立即停止一条线程,然而停止线程却显得尤为重要,如取消一个耗时操作。因此,Java提供了一种用于停止线程的协商机制----中断,也即中断标识协商机制
-
- 中断只是一种协作协商机制,Java没有给中断增加任何语法,中断的过程完全需要程序员自行实现。若要中断一个线程,你需要手动调用该线程interrupt方法,该方法也仅仅是将该线程对象的中断标识设置为true,接着你需要自己写代码不断检测当前线程的标识位,如果为true,表示别的线程请求这条线程中断,此时究竟应该做什么需要你自己写代码实现。
- 每个线程对象都有一个中断标识位,用于表示线程是否被中断;该标识位为true表示中断,为false表示未中断;通过调用线程对象的interrupt方法将该线程的标识位设置为true;可以在别的线程中调用,也可以在自己的线程中调用。
1.3 中断的相关API方法之三大方法说明
- public void interrupt()
-
- 实例方法 Just to set the interrupt flag
- 实例方法仅仅是设置线程的中断状态为true,发起一个协商而不会立刻停止线程
- public static boolean interrupted()
-
- 静态方法 Thread.interrupted();
- 判断线程是否被中断并清除当前中断状态(做了两件事情)
-
-
- 1.返回当前线程的中断状态,测试当前线程是否已被中断
- 2.将当前线程的中断状态清零并重新设置为false,清除线程的中断状态
- 3.这个方法有点不好理解在于如果连续两次调用此方法,则第二次返回false,因为连续调用两次的结果可能不一样
-
- public boolean isInterrupted()
-
- 实例方法
- 判断当前线程是否被中断(通过检查中断标志位)
1.4.如何停止中断运行中的线程?
1.4.1通过一个volatile变量实现
package com.bilibili.juc.interrupt;
import java.util.concurrent.TimeUnit;
public class InterruptDemo {
static volatile boolean isStop = false; // volatile修饰的变量具有可见性
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(Thread.currentThread().getName() + "--------hello volatile--------");
}
}, "t1").start();
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> isStop = true, "t2").start();
}
}
输出结果:
t1--------hello volatile--------
t1--------hello volatile--------
t1--------hello volatile--------
t1--------hello volatile--------
...
t1--------hello volatile--------
t1--------hello volatile--------
t1--------hello volatile--------
t1--------hello volatile--------
t1 isStop的值被改为true,程序停止
1.4.2通过AutomicBoolean
package com.bilibili.juc.interrupt;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public class InterruptDemo2 {
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(Thread.currentThread().getName() + "--------hello atomicBoolean--------");
}
}, "t1").start();
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> atomicBoolean.set(true), "t2").start();
}
}
输出结果:
t1--------hello atomicBoolean--------
t1--------hello atomicBoolean--------
t1--------hello atomicBoolean--------
t1--------hello atomicBoolean--------
...
t1--------hello atomicBoolean--------
t1--------hello atomicBoolean--------
t1--------hello atomicBoolean--------
t1--------hello atomicBoolean--------
t1 atomicBoolean的值被改为true,程序停止
1.4.3通过Thread类自带的中断API实例方法实现
在需要中断的线程中不断监听中断状态,一旦发生中断,就执行相应的中断处理业务逻辑stop线程。
package com.bilibili.juc.interrupt;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public class InterruptDemo3 {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().getName() + "\t isInterrupted的值被改为true,程序停止");
break;
}
System.out.println(Thread.currentThread().getName() + "--------hello interrupt api--------");
}
}, "t1");
t1.start();
System.out.println("--------t1的默认中断标识位:" + t1.isInterrupted());
try {
TimeUnit.MILLISECONDS.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(t1::interrupt, "t2").start(); // t2向t1发出协商,将t1线程的中断状态为true
// t1.interrupt(); // 也可以自己调用interrupt()方法将自己线程的中断状态为true
}
}
输出结果:
--------t1的默认中断标识位:false
t1--------hello interrupt api--------
t1--------hello interrupt api--------
t1--------hello interrupt api--------
t1--------hello interrupt api--------
...
t1--------hello interrupt api--------
t1--------hello interrupt api--------
t1--------hello interrupt api--------
t1--------hello interrupt api--------
t1 isInterrupted的值被改为true,程序停止
1.5.interrupt和isInterrupted方法源码分析
1.5.1.interrupt()方法
public void interrupt() {
if (this != Thread.currentThread())
checkAccess();
synchronized (blockerLock) {
Interruptible b = blocker;
if (b != null) {
interrupt0(); // Just to set the interrupt flag
b.interrupt(this);
return;
}
}
interrupt0();
}
private native void interrupt0(); // 本地方法
注意:
中断此线程
除非当前线程正在中断(始终允许),否则将调用此线程的checkAccess方法,这可能会导致抛出SecurityException
如果该线程阻塞的调用Object类的wait(),wait(long)或wait(long, int)方法,或Thread类的join(),join(long),join(long, int),sleep(long),或sleep(long, int)方法,那么它的中断状态将被清除(也就是说中断失败,中断标志还是false!),并目将收到InterruptedException。(也就是说某个线程正在调用以上方法处于阻塞状态,其他线程突然调用interrupt方法将其打断,该线程将会被打断退出阻塞状态,并报InterruptedException异常)
如果在InterruptibleChannel上的I/O操作中阻止该丝程,则通道将关闭,线程的中断状态将被设置,线程将收到ClosedByInterruptException
如果该线程在Selector中被阻塞,则线程的中断状态将被设置,它将立即从选择操作返回,可能具有非零值,就像调用选择器的wakeup方法一样。
如果以前的条件都不成立,则将设置该线程的中断状态。
中断不活动的线程不会产生任何影响。也就是说打断不活动的线程没有任何意义。
异常:SecurityException —— 如果当前线程无法修改此线程
1.5.2.isInterrupted()方法
/**
测试此线程是否已中断
线程的interrupted状态不受此方法影响
返回true代表此线程已经被中断,false则此线程未被中断
*/
public boolean isInterrupted() {
return isInterrupted(false);
}
/**
测试某些线程是否已中断。中断状态是否复位取决于传递的ClearInterrupted的值
*/
private native boolean isInterrupted(boolean ClearInterrupted); // 本地方法
总结
具体来说,当一个线程调用interrupt()方法时:
1.如果线程处于正常活动状态,那么会将该线程的中断标识设置为true,仅此而已。被设置中断标识的线程将继续运行,不受影响。
所以,interrupt()方法并不能真正的中断线程,需要被调用的线程自己进行配合才行(比如说加一段判断中断标志,如果为true就知道要被打断,从而写一个中断线程的逻辑)。
2.如果线程处于被阻塞状态(例如处于sleep、wait、join等状态),在别的线程中调用当前线程对象的interrupt()方法,那么线程将立即退出被阻塞状态,并抛出一个InterruptedException异常,但中断标志被清除,还是false状态。
中断失败导致死循环的样例
/**
*1. 中断标志位默认为false
* 2.t2对t1发出中断协商 t1.interrupt();
* 3. 中断标志位为true: 正常情况 程序停止
* 中断标志位为true 异常情况,.InterruptedException ,将会把中断状态清楚,中断标志位为false
* 4。需要在catch块中,再次调用interrupt()方法将中断标志位设置为false;
*/
package com.bilibili.juc.interrupt;
import java.util.concurrent.TimeUnit;
public class InterruptDemo5 {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
while (true) {
if (Thread.currentThread().isInterrupted()) {
System.out.println(Thread.currentThread().getName() + "\t中断标志位为:" + Thread.currentThread().isInterrupted() + "\t程序停止");
break;
}
// sleep方法抛出InterruptedException后,中断标识也被清空置为false,如果没有在
// catch方法中调用interrupt方法再次将中断标识置为true,这将导致无限循环了
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// Thread.currentThread().interrupt();
e.printStackTrace();
if (Thread.currentThread().isInterrupted()){
System.out.println("线程:" + Thread.currentThread().getName() + "\t结束工作");
break;
}
}
System.out.println("--------hello InterruptDemo5--------");
}
}, "t1");
t1.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> t1.interrupt(), "t2").start();
}
}
输出结果:
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.bilibili.juc.interrupt.InterruptDemo5.lambda$main$0(InterruptDemo5.java:23)
at java.lang.Thread.run(Thread.java:748)
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
... // 程序未停止
提出疑问:为什么程序未停止,产生了死循环?
解决:放开注释 Thread.currentThread().interrupt();
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
--------hello InterruptDemo5--------
t1 中断标志位为:true 程序停止
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at com.bilibili.juc.interrupt.InterruptDemo5.lambda$main$0(InterruptDemo5.java:23)
at java.lang.Thread.run(Thread.java:748)
分析:
1.中断标志位,默认为false
2.t2对t1发出中断协商,t2调用t1.interrupt(),中断标志位设置为true
3.中断标志位为true:正常情况,程序停止
4.中断标志位为true:异常情况,InterruptedException ,将会把中断状态清除,并收到InterruptedException,中断标志位为false,此时导致无限循环
5.需要在catch块中,再次调用interrupt()方法将中断标志位设置为true,二次调用停止程序
ps:具体也可以见之前interrupt()方法源码分析
总结
中断只是一种协商机制,修改中断标识位仅此而已,不是立刻stop打断
sleep方法抛出InterruptedException后,中断标识也被清空置为false,如果没有在catch方法中调用interrupt方法再次将中断标识置为true,这将导致无限循环了。
1.5.3.interrupted()方法
源码
/**
测试当前线程是否已中断。该方法清除线程的中断状态。换句话说,如果这个方法被连续调用两次,第二次调用将返回false(除非当前线程再次被中断,在第一次调用清除了中断状态之后,在第二次调用检查它之前)
返回true代表此线程已经被中断,false则此线程未被中断
*/
public static boolean interrupted() {
return currentThread().isInterrupted(true);
}
/**
测试某些线程是否已中断。中断状态是否复位取决于传递的ClearInterrupted的值
*/
private native boolean isInterrupted(boolean ClearInterrupted);
样例code:
package com.bilibili.juc.interrupt;
public class InterruptDemo6 {
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + "\t" + Thread.interrupted());
System.out.println(Thread.currentThread().getName() + "\t" + Thread.interrupted());
System.out.println("----1----");
Thread.currentThread().interrupt(); // 中断标识位设置为true
System.out.println("----2----");
System.out.println(Thread.currentThread().getName() + "\t" + Thread.interrupted());
System.out.println(Thread.currentThread().getName() + "\t" + Thread.interrupted());
}
}
输出结果:
main false
main false
----1----
----2----
main true
main false
都会返回中断状态,两者对比
对于静态方法Thread.interrupted()和实例方法Thread.currentThread().isInterrupted()区别在于:
静态方法interrupted将会清除中断状态(传入的参数ClearInterrupted为true)
实例方法isInterrupted则不会(传入的参数ClearInterrupted为false)
ClearInterrupted参数为是否清除线程状态,清除以后线程状态就为false
1.6. 总结
- public void interrupt() 是一个实例方法,它通知目标线程中断,也仅仅是设置目标线程的中断标志位为true
- public boolean isInterrupted() 是一个实例方法,它判断当前线程是否被中断(通过检查中断标志位)并获取中断标志
- public static boolean interrupted() 是一个静态方法,返回当前线程的中断真实状态(boolean类型)后会将当前线程的中断状态设为false,此方法调用之后会清楚当前线程的中断标志位的状态(将中断标志置为false了),返回当前值并清零置为false。
2 .LockSupport
2.1.LockSupport概念
LockSupport是Java并发编程中提供的一个类,用于支持线程的阻塞和唤醒操作。LockSupport类中的静态方法可以让线程暂停执行(阻塞)或者唤醒指定线程。
LockSupport类主要提供以下两个主要方法:
1. park():使当前线程暂停执行,相当于让线程进入等待状态。当调用park()方法时,线程会阻塞,直到调用unpark(Thread)方法唤醒它。
2. unpark(Thread thread):唤醒指定的线程,即解除该线程的阻塞状态。如果调用unpark()方法时,指定的线程处于阻塞状态,则会被唤醒。如果调用unpark()方法时,指定的线程还未调用park()方法进入阻塞状态,那么下次调用park()方法时,仍然会立即返回。
LockSupport类提供了一种更加灵活、可靠的线程阻塞和唤醒的机制,可以替代传统的wait()和notify()方法。但需要注意的是,LockSupport类不会导致死锁,因为它不会造成线程持有任何锁。使用LockSupport类时,一般需要在合适的位置进行对应的park()和unpark()操作,以确保线程能够正确的进行阻塞和唤醒。
2.2.线程等待唤醒机制
2.2.1.三种让线程等待和唤醒的方法
- 方式一:使用Object中的wait()方法让线程等待,使用Object中的notify()方法唤醒线程
- 方式二:使用JUC包中的Condition的await()方法让线程等待,使用signal()方法唤醒线程
- 方式三:LockSupport类可以阻塞当前线程以及唤醒指定被阻塞的线程
2.2.2.wait和notify的实现线程等待和唤醒
首先wait方法和notify方法是Object类的final方法,因此所有类都有这两个方法。之前我们说过Java中所有对象都可以作为锁对象,就是因为每个对象都有一个ObjectMonitor。
同步代码块样例代码1
public static void main(String[] args) throws InterruptedException {
Object obj = new Object();
Thread t1 = new Thread(() -> {
synchronized (obj) {
System.out.println(Thread.currentThread().getName() + "线程获取obj对象");
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + "线程退出等待");
}, "t1");
t1.start();
//停一秒,确保t1线程先拿到锁对象
Thread.sleep(3000);
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "线程获取obj对象");
synchronized (obj) {
obj.notify();//唤醒t1线程
System.out.println(Thread.currentThread().getName() + "线程唤醒t1线程");
}
}, "t2").start();
}
输出结果:
t1线程获取obj对象
t2线程获取obj对象
t2线程唤醒t1线程
t1线程退出等待
同步方法样例代码2
public static void main(String[] args) throws InterruptedException {
LockDemo lockDemo = new LockDemo();
new Thread(() -> {
try {
lockDemo.f();
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t1").start();
Thread.sleep(1000);
new Thread(() -> {
lockDemo.f2();
}).start();
}
public synchronized void f() throws InterruptedException {
System.out.println("f方法正在等待");
wait();
System.out.println("f方法退出等待");
}
public synchronized void f2() {
System.out.println("f2方法通知等待线程");
notify();
}
运行结果:
f方法正在等待
f2方法通知等待线程
f方法退出等待
注意几点:
1.这里调用wait和notify方法的应该是锁对象,因为真正含有ObjectMonitor的是这里的obj对象,它里面的monitor中的waiSet存放正在等待的线程(这里就是t1)。
2.必须先调用wait再调用notify,否则线程t1没有人唤醒它,它就一直处于等待状态,无法结束线程
3.wait和notify都必须在同步代码块或者同步方法中使用,原因很简单,必须先确定锁对象才知道ObjectMonitor。在样例1中锁对象就是obj,而在样例2中,线程12中调用f方法(wait方法)和调用f2方法(notify方法)的实例是同一个lockDemo,如果不是同一个就会出现问题!这里锁对象就不是同一个了,线程t1就不会结束!!!
2.2.3.Condition接口中的await和signal方法实现线程的等待和唤醒
使用样例
public static void main(String[] args) throws InterruptedException {
Lock lock = new ReentrantLock();
Condition condition = lock.newCondition();
new Thread(() -> {
lock.lock();
try {
System.out.println(Thread.currentThread().getName() + "线程正在等待");
condition.await();
System.out.println(Thread.currentThread().getName() + "线程被唤醒");
} catch (Exception e) {
} finally {
lock.unlock();
}
}, "t1").start();
Thread.sleep(1000);
new Thread(() -> {
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+"线程正在唤醒等待线程");
condition.signal();
} catch (Exception e) {
} finally {
lock.unlock();
}
}, "t2").start();
}
运行结果:
t1线程正在等待
t2线程正在唤醒等待线程
t1线程被唤醒
总结
Condition中的线程等待和唤醒方法,需要先获取锁
一定要先await后signal,不要反了,否则程序无法执行,无法唤醒
2.2.4.LockSupport类中的park等待和unpark唤醒
上述两个对象Object和Condition使用的限制条件
- 线程需要先获得并持有锁,必须在锁块(synchronized或lock)中
- 必须要先等待后唤醒,线程才能够被唤醒
LockSupport是什么
LockSupport 是用于创建锁和其他同步类的基本线程阻塞原语
LockSupport类使用了一种名为Permit(许可)的概念来做到阻塞和唤醒线程的功能,每个线程都有一个许可(Permit)
但是与Semaphore不同,许可证只能有一个,累加上限是1。
这些方法都是静态方法,其中park() 和 unpark(Thread thread) 这两个方法比较常用,LockSupport.park() 方法在哪个线程中被调用,哪个线程就会被检查,检查当前线程是否有许可证permit,如果有就放行,如果没有,该线程就会被阻塞,等待其他线程调用LockSupport.unpark(Thread thread) 方法 (传入正在等待的线程) 给等待线程发放许可证,相当于通知,让他结束等待。
因此park和unpark就相当于等待和唤醒。
样例1
package com.imooc.springcloud.locksupport;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
public class ParkDemo {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
System.out.println(Thread.currentThread().getName() + "\t --------come in");
LockSupport.park();
System.out.println(Thread.currentThread().getName() + "\t --------被唤醒");
}, "t1");
t1.start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(() -> {
LockSupport.unpark(t1);
System.out.println(Thread.currentThread().getName() + "\t --------发出通知");
}, "t2").start();
}
}
输出结果:
t1 --------come in
t1 --------被唤醒
t2 --------发出通知
样例2,先unpark发放通行证,Permit设为1,再park,消耗Permit
package com.imooc.springcloud.locksupport;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;
public class ParkDemo2 {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "\t --------come in,当前时间:" + System.currentTimeMillis());
LockSupport.park();
System.out.println(Thread.currentThread().getName() + "\t --------被唤醒,当前时间:" + System.currentTimeMillis());
}, "t1");
t1.start();
new Thread(() -> {
LockSupport.unpark(t1);
System.out.println(Thread.currentThread().getName() + "\t --------发出通知");
}, "t2").start();
}
}
输出结果:
t2 --------发出通知
t1 --------come in,当前时间:1699280068622
t1 --------被唤醒,当前时间:1699280068622
可以看到,park(阻塞)形同虚设,这是因为提前unpark,先把Permit设为1了。park的时候直接放行了。类似于高速公路ETC,提前买好了通行证,直接就放行了。但通行证只有一个,最多也只能有一个!每次park就会消耗一个。因为Permit最多只能有一个,所以park、unpark需要成对出现,如果同时先出现两个unpark再两次park,由于上限为1,就会出现线程没人通知二导致一直阻塞!(如果先park两次,再unpark两次,线程是可以被正常唤醒的,但不建议这么做,park和unpark还是成双成对出现比较好!)
结论
1.满足正常无锁块的要求
2.之前错误的先唤醒后等待,LockSupport照样支持(t1线程sleep方法3秒后醒来,执行park无效,没有阻塞效果,因为先执行了unpark(t1)导致上面的park方法形同虚设,无效,所以输出时间一样【类似高速公路的ETC,提前买好了通行证unpark,到闸机处直接抬起栏杆放行了,没有park拦截了】)
3.成双成对出现要牢记