多线程进阶学习07------线程中断与等待唤醒
创始人
2025-06-01 14:38:49
0

线程的中断协商机制

什么是中断

一个线程不应该由其他线程来强制中断或停止,而是应该由线程自己自行停止。所以,Thread.stop、Thread.suspend、Thread. resume都已经被废弃了。

在Java中没有办法立即停止一条线程,然而停止线程却显得尤为重要,如取消一个耗时操作。
因此,Java提供了一种用于停止线程的机制即中断。中断只是一种协作机制,Java没有给中断增加任何语法,中断的实现完全需要程序员自己实现。

1、每个线程对象中都有一个标识,用于标识线程是否被中断;该标识位为true表示中断,为false表示未中断;若要中断协商一个线程,你需要手动调用该线程的interrupt方法,该方法也仅仅是
将线程对象的中断标识设为true。
2、interrupt可以在别的线程中调用,也可以在自己的线程中调用

interrupt

线程t1线程t2,当线程t2调用t1.interrupt()时

中断协商:如果t1线程处于正常活动状态,当线程t2调用t1.interrupt()时,那么会将t1线程的中断标志设置为true,仅此而已。t1线程将继续正常运行不受影响

isInterrupted

通过检查中断标志位判断当前线程是否被中断
●若中断标志为true,则isInterrupted返回true
●若中断标志为false,则isInterrupted返回false

静态方法interrupted

判断线程是否被中断,并清除当前中断状态,这个方法做了两件事:
●返回当前线程的中断状态
●将当前线程的中断状态重置即设为false

假设有两个线程A、B,线程B调用了interrupt方法。
后面如果我们连接调用两次interrupted方法,第一次会返回true,然后这个方法会将中断标识位设置位false,
所以第二次调用interrupted将返回false

中断运行中的线程

volatile

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("t1 -----hello volatile");}}, "t1").start();//暂停毫秒try {TimeUnit.MILLISECONDS.sleep(20);} 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("t1 -----hello atomicBoolean");}}, "t1").start();//暂停毫秒try {TimeUnit.MILLISECONDS.sleep(20);} catch (InterruptedException e) {e.printStackTrace();}new Thread(() -> {atomicBoolean.set(true);}, "t2").start();}

interrupt+isInterrupted

 static volatile boolean isStop = false;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("t1 -----hello interrupt api");}}, "t1");t1.start();System.out.println("-----t1的默认中断标志位:" + t1.isInterrupted());//暂停毫秒try {TimeUnit.MILLISECONDS.sleep(20);} catch (InterruptedException e) {e.printStackTrace();}//t2向t1发出协商,将t1的中断标志位设为true希望t1停下来new Thread(() -> {t1.interrupt();}, "t2").start();//t1.interrupt();,t1也可以自己给自己协商}

等待唤醒

线程等待与唤醒的方式演进:

在这里插入图片描述
LockSupport是用来创建锁和其他同步类的基本线程阻塞原语。LockSupport类使用了一种名为Permit(许可)的概念来做到阻塞和唤醒线程的功能,每个线程都有一个许可(permit),permit只有两个值1和零,默认是零。可以把许可看成是一种(0,1)信号量(Semaphore),但与Semaphore不同的是,许可的累加上限是1

阻塞方法park:

①. permit默认是0,所以一开始调用park()方法,当前线程就会阻塞,直到别的线程将当前线程的permit设置为1时, park方法会被唤醒,然后会将permit再次设置为0并返回
②. static void park( ):底层是unsafe类native方法

唤醒方法unpark:

①. 调用unpark(thread)方法后,就会将thread线程的许可permit设置成1(注意多次调用unpark方法,不会累加,permit值上限是1)会自动唤醒thread线程,即之前阻塞中的LockSupport.park()方法失效
②. static void unpark( ):底层是unsafe类native方法

LockSupport它的解决的痛点:
①. LockSupport不用持有锁块,在代码书写方面不用加锁
②. 唤醒与阻塞的先后顺序,即使先调用唤醒再调用阻塞也不会导致程序卡死报异常,因为unpark获得了一个凭证,之后再调用park方法,就可以名正言顺的依据凭证消费

demo

public class LockSupportDemo {static int x = 0;static int y = 0;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();//暂停几秒钟线程//try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }new Thread(() -> {LockSupport.unpark(t1);System.out.println(Thread.currentThread().getName() + "\t ----发出通知");}, "t2").start();}
}

生产者与消费者

synchronized

public class ProductorAndConsumer {public static void main(String[] args) {Market market = new Market();Productor productor = new Productor(market);Consumer consumer = new Consumer(market);new Thread(productor, "生产者A").start();new Thread(consumer, "消费者B").start();new Thread(productor, "生产者C").start();new Thread(consumer, "消费者D").start();}
}//商店
class Market {//某件商品数量,最开始为0private int product = 0;//进货方法,在多线程环境下,如果不加锁会产生线程安全问题,这里加synchronized锁public synchronized void get() {//限定商店容量为10while (product > 10) {System.out.println("仓库已满!");//当仓库已满,需要停止生产try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(Thread.currentThread().getName() + "进货成功!-->" + ++product);//当进货成功,就需要唤醒this.notifyAll();}//出售方法public synchronized void sale() {while (product <= 0) {System.out.println("已售罄!");//售罄之后需要停止去生产try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.println(Thread.currentThread().getName() + "出售成功-->" + --product);//出售成功之后需要生产this.notifyAll();}
}//生产者,生产者不可能只有一个,所以是多线程的
class Productor implements Runnable {private Market market;public Productor(Market market) {this.market = market;}@Overridepublic void run() {//一次买15个for (int i = 0; i < 15; i++) {market.get();}}
}//消费者
class Consumer implements Runnable {private Market market;public Consumer() {}public Consumer(Market market) {this.market = market;}@Overridepublic void run() {//一次买10个for (int i = 0; i < 10; i++) {market.sale();}}
}

Lock

/** 使用Lock代替Synchronized来实现新版的生产者和消费者模式 !* */
@SuppressWarnings("all")
public class ThreadWaitNotifyDemo {public static void main(String[] args) {AirCondition airCondition = new AirCondition();new Thread(() -> {for (int i = 0; i < 10; i++) airCondition.decrement();}, "线程A").start();new Thread(() -> {for (int i = 0; i < 10; i++) airCondition.increment();}, "线程B").start();new Thread(() -> {for (int i = 0; i < 10; i++) airCondition.decrement();}, "线程C").start();new Thread(() -> {for (int i = 0; i < 10; i++) airCondition.increment();}, "线程D").start();}
}class AirCondition {private int number = 0;//定义Lock锁对象final Lock lock = new ReentrantLock();final Condition condition = lock.newCondition();//生产者,如果number=0就 number++public void increment() {lock.lock();try {//1.判断while (number != 0) {try {condition.await();//this.wait();} catch (InterruptedException e) {e.printStackTrace();}}//2.干活number++;System.out.println(Thread.currentThread().getName() + ":\t" + number);//3.唤醒condition.signalAll();//this.notifyAll();} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}}//消费者,如果number=1,就 number--public void decrement() {lock.lock();try {//1.判断while (number == 0) {try {condition.await();//this.wait();} catch (InterruptedException e) {e.printStackTrace();}}//2.干活number--;System.out.println(Thread.currentThread().getName() + ":\t" + number);//3.唤醒condition.signalAll();//this.notifyAll();} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}}
}

Lock带顺序的生产者与消费者

/*多个线程之间按顺序调用,实现A->B->C
三个线程启动,要求如下:AA打印5次,BB打印10次,CC打印15次接着AA打印5次,BB打印10次,CC打印15次....来10轮
* */
public class ThreadOrderAccess {public static void main(String[] args) {ShareResource shareResource = new ShareResource();new Thread(() -> {for (int i = 1; i <= 10; i++) shareResource.print5();}, "线程A").start();new Thread(() -> {for (int i = 1; i <= 10; i++) shareResource.print10();}, "线程B").start();new Thread(() -> {for (int i = 1; i <= 10; i++) shareResource.print15();}, "线程C").start();}
}class ShareResource {//设置一个标识,如果是number=1,线程A执行...private int number = 1;Lock lock = new ReentrantLock();Condition condition1 = lock.newCondition();Condition condition2 = lock.newCondition();Condition condition3 = lock.newCondition();public void print5() {lock.lock();try {//1.判断while (number != 1) {condition1.await();}//2.干活for (int i = 1; i <= 5; i++) {System.out.println(Thread.currentThread().getName() + ":\t" + i);}//3.唤醒number = 2;condition2.signal();} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}}public void print10() {lock.lock();try {//1.判断while (number != 2) {condition2.await();}//2.干活for (int i = 1; i <= 10; i++) {System.out.println(Thread.currentThread().getName() + ":\t" + i);}//3.唤醒number = 3;condition3.signal();} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}}public void print15() {lock.lock();try {//1.判断while (number != 3) {condition3.await();}//2.干活for (int i = 1; i <= 15; i++) {System.out.println(Thread.currentThread().getName() + ":\t" + i);}//3.唤醒number = 1;condition1.signal();} catch (Exception e) {e.printStackTrace();} finally {lock.unlock();}}
}

相关内容

热门资讯

linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
C++ 机房预约系统(六):学... 8、 学生模块 8.1 学生子菜单、登录和注销 实现步骤: 在Student.cpp的...
JAVA多线程知识整理 Java多线程基础 线程的创建和启动 继承Thread类来创建并启动 自定义Thread类的子类&#...
【洛谷 P1090】[NOIP... [NOIP2004 提高组] 合并果子 / [USACO06NOV] Fence Repair G ...
国民技术LPUART介绍 低功耗通用异步接收器(LPUART) 简介 低功耗通用异步收发器...
城乡供水一体化平台-助力乡村振... 城乡供水一体化管理系统建设方案 城乡供水一体化管理系统是运用云计算、大数据等信息化手段࿰...
程序的循环结构和random库...   第三个参数就是步长     引入文件时记得指明字符格式,否则读入不了 ...
中国版ChatGPT在哪些方面... 目录 一、中国巨大的市场需求 二、中国企业加速创新 三、中国的人工智能发展 四、企业愿景的推进 五、...
报名开启 | 共赴一场 Flu... 2023 年 1 月 25 日,Flutter Forward 大会在肯尼亚首都内罗毕...
汇编00-MASM 和 Vis... Qt源码解析 索引 汇编逆向--- MASM 和 Visual Studio入门 前提知识ÿ...
【简陋Web应用3】实现人脸比... 文章目录🍉 前情提要🌷 效果演示🥝 实现过程1. u...
前缀和与对数器与二分法 1. 前缀和 假设有一个数组,我们想大量频繁的去访问L到R这个区间的和,...
windows安装JDK步骤 一、 下载JDK安装包 下载地址:https://www.oracle.com/jav...
分治法实现合并排序(归并排序)... 🎊【数据结构与算法】专题正在持续更新中,各种数据结构的创建原理与运用✨...
在linux上安装配置node... 目录前言1,关于nodejs2,配置环境变量3,总结 前言...
Linux学习之端口、网络协议... 端口:设备与外界通讯交流的出口 网络协议:   网络协议是指计算机通信网...
Linux内核进程管理并发同步... 并发同步并发 是指在某一时间段内能够处理多个任务的能力,而 并行 是指同一时间能够处理...
opencv学习-HOG LO... 目录1. HOG(Histogram of Oriented Gradients,方向梯度直方图)1...
EEG微状态的功能意义 导读大脑的瞬时全局功能状态反映在其电场结构上。聚类分析方法一致地提取了四种头表面脑电场结构ÿ...
【Unity 手写PBR】Bu... 写在前面 前期积累: GAMES101作业7提高-实现微表面模型你需要了解的知识 【技...