【多线程】线程间通信 之虚假唤醒和中断

2024-09-02 19:12

本文主要是介绍【多线程】线程间通信 之虚假唤醒和中断,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

两个线程,可以操作初始值为0的一个变量,实现一个线程对该变量+1,一个线程对该变量-1,实现交替,来10轮,变量初始值为0,以实现此问题作为引入,简化我们的理解

文章目录

    • 一、两个线程synchronized写法-结果无问题
    • 二(一)、四个线程synchronized写法-问题及解决办法
    • 二(二)、4线程问题 解决办法1:使用while进行条件判断
    • 二(三)、4线程问题 解决办法2:使用Lock和Condition实现线程间通信

一、两个线程synchronized写法-结果无问题

package com.atguigu.signcenter.thread;/*** 线程之间的通信-两个线程synchronized写法* @author: jd* @create: 2024-09-02*/
public class ThreadWaitNotifyDemo {public static void main(String[] args) {AirConditioner airConditioner = new AirConditioner();new Thread(() -> {for (int i = 0; i < 10; i++) {try {airConditioner.increment();} catch (InterruptedException e) {e.printStackTrace();}}}, "A").start();new Thread(() -> {for (int i = 0; i < 10; i++) {try {airConditioner.decrement();} catch (InterruptedException e) {e.printStackTrace();}}}, "B").start();}
}class AirConditioner {  // 资源类private int number = 0;public synchronized void increment() throws InterruptedException {// 1. 判断if (number != 0) {this.wait();}// 2. 干活number++;System.out.println(Thread.currentThread().getName() + "\t" + number);// 3. 通知this.notifyAll();}public synchronized void decrement() throws InterruptedException {// 1. 判断if (number == 0) {this.wait();}// 2. 干活number--;System.out.println(Thread.currentThread().getName() + "\t" + number);// 3. 通知this.notifyAll();}
}

结果:

A	1
B	0
A	1
B	0
A	1
B	0
A	1
B	0
A	1
B	0
A	1
B	0
A	1
B	0
A	1
B	0
A	1
B	0
A	1
B	0

二(一)、四个线程synchronized写法-问题及解决办法

换成4个线程会导致错误,虚假唤醒。
原因:在java多线程判断时,不能用if,程序出事出在了判断上面,突然有一添加的线程进到if了,突然中断了交出控制权,没有进行验证,而是直接走下去了,加了两次,甚至多次。
在这里插入图片描述

中断和虚假唤醒是可能产生的,所以要用loop循环,if只判断一次,while是只要唤醒就要拉回来再判断一次。if换成while。(也就是说在四个线程下,有可能两个increment线程都在if中wait,当其被唤醒时,不会再次判断number是否满足条件,而直接执行number++,因此会导致number大于1的情况,同理也会出现number小于0的情况)

如果使用if判断,则会导致虚假唤醒:代码及现象

package com.atguigu.signcenter.thread;/*** 线程之间的通信-两个、四个线程synchronized写法* @author: jd* @create: 2024-09-02*/
public class ThreadWaitNotifyDemo {public static void main(String[] args) {AirConditioner airConditioner = new AirConditioner();new Thread(() -> {for (int i = 0; i < 10; i++) {try {airConditioner.increment();} catch (InterruptedException e) {e.printStackTrace();}}}, "A").start();new Thread(() -> {for (int i = 0; i < 10; i++) {try {airConditioner.decrement();} catch (InterruptedException e) {e.printStackTrace();}}}, "B").start();new Thread(() -> {for (int i = 0; i < 10; i++) {try {airConditioner.increment();} catch (InterruptedException e) {e.printStackTrace();}}}, "C").start();new Thread(() -> {for (int i = 0; i < 10; i++) {try {airConditioner.decrement();} catch (InterruptedException e) {e.printStackTrace();}}}, "D").start();}
}class AirConditioner {  // 资源类private int number = 0;public synchronized void increment() throws InterruptedException {// 1. 判断if (number != 0) {this.wait();}// 2. 干活number++;System.out.println(Thread.currentThread().getName() + "\t" + number);// 3. 通知this.notifyAll();}public synchronized void decrement() throws InterruptedException {// 1. 判断if (number == 0) {this.wait();}// 2. 干活number--;System.out.println(Thread.currentThread().getName() + "\t" + number);// 3. 通知this.notifyAll();}
}

现象

A	1
B	0
A	1
B	0
C	1
B	0
A	1
B	0
C	1
D	0
B	-1
B	-2
B	-3
B	-4
B	-5
B	-6
A	-5
D	-6
D	-7
D	-8
D	-9
D	-10
D	-11
D	-12
D	-13
D	-14
C	-13
A	-12
C	-11
A	-10
C	-9
A	-8
C	-7
A	-6
C	-5
A	-4
C	-3
A	-2
C	-1

图示为什么会出现问题
在使用if判断两个线程的情况下,阻塞的线程只有两种情况,此时不会出现任何问题;
而使用if在四个线程的情况下,可能存在这种情况:

  1. 最开始+线程进行了增加操作NotifyAll;
  2. 此时+'线程抢占到执行权,进入if判断进入阻塞状态;
  3. +线程又抢到了执行权,同样进入if判断阻塞;
  4. -线程抢占执行权进行减操作,NotifyAll;
  5. +'线程抢占执行权,进行增加操作,NotifyAll;
  6. +线程抢占执行权,进行增加操作 (此时便出现了number=2的情况)
    使用while就不会出现这种问题,因为在NotifyAll线程激活运行后,会进行二次判断!
    在这里插入图片描述

二(二)、4线程问题 解决办法1:使用while进行条件判断

解决此问题:
使用while进行条件判断

  1. 高内聚第耦合的前提下,线程操作资源类
  2. 判断/干活/通知
  3. 多线程交互中,必须要防止多线程的虚假唤醒,也即(在多线程的判断中不许用if只能用while)
    解决代码:
package com.atguigu.signcenter.thread;/*** 线程之间的通信-两个、四个线程synchronized写法* @author: jd* @create: 2024-09-02*/
public class ThreadWaitNotifyDemo {public static void main(String[] args) {AirConditioner airConditioner = new AirConditioner();new Thread(() -> {for (int i = 0; i < 10; i++) {try {airConditioner.increment();} catch (InterruptedException e) {e.printStackTrace();}}}, "A").start();new Thread(() -> {for (int i = 0; i < 10; i++) {try {airConditioner.decrement();} catch (InterruptedException e) {e.printStackTrace();}}}, "B").start();new Thread(() -> {for (int i = 0; i < 10; i++) {try {airConditioner.increment();} catch (InterruptedException e) {e.printStackTrace();}}}, "C").start();new Thread(() -> {for (int i = 0; i < 10; i++) {try {airConditioner.decrement();} catch (InterruptedException e) {e.printStackTrace();}}}, "D").start();}
}
/*
class AirConditioner {  // 资源类private int number = 0;public synchronized void increment() throws InterruptedException {// 1. 判断if (number != 0) {this.wait();}// 2. 干活number++;System.out.println(Thread.currentThread().getName() + "\t" + number);// 3. 通知this.notifyAll();}public synchronized void decrement() throws InterruptedException {// 1. 判断if (number == 0) {this.wait();}// 2. 干活number--;System.out.println(Thread.currentThread().getName() + "\t" + number);// 3. 通知this.notifyAll();}*/class AirConditioner {  // 资源类private int number = 0;public synchronized void increment() throws InterruptedException {// 1. 判断while (number != 0) {this.wait();}// 2. 干活number++;System.out.println(Thread.currentThread().getName() + "\t" + number);// 3. 通知this.notifyAll();}public synchronized void decrement() throws InterruptedException {// 1. 判断while (number == 0) {this.wait();}// 2. 干活number--;System.out.println(Thread.currentThread().getName() + "\t" + number);// 3. 通知this.notifyAll();}
}

正常结果:

A	1
B	0
A	1
B	0
A	1
B	0
C	1
B	0
A	1
B	0
C	1
B	0
A	1
D	0
C	1
B	0
A	1
D	0
C	1
B	0
A	1
D	0
C	1
B	0
A	1
D	0
C	1
B	0
A	1
D	0
C	1
D	0
A	1
D	0
C	1
D	0
C	1
D	0
C	1
D	0

二(三)、4线程问题 解决办法2:使用Lock和Condition实现线程间通信

通过Java8的Lock和Condition接口(await、signal、signalAll),可以替换synchronized与Object monitor方法(wait、notify、notifyAll)
在这里插入图片描述
这里我们还是使用3.2中的例子,4个线程,两个打印1两个打印0,让其交替打印,分别打印十次

package com.atguigu.signcenter.thread;import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;/*** @author: jd* @create: 2024-09-02*/
public class ThreadWaitNotifyDemo2 {public static void main(String[] args) {AirConditioner2 airConditioner = new AirConditioner2();new Thread(() -> {for (int i = 0; i < 10; i++) {try {airConditioner.increment();} catch (InterruptedException e) {e.printStackTrace();}}}, "A").start();new Thread(() -> {for (int i = 0; i < 10; i++) {try {airConditioner.decrement();} catch (InterruptedException e) {e.printStackTrace();}}}, "B").start();new Thread(() -> {for (int i = 0; i < 10; i++) {try {airConditioner.increment();} catch (InterruptedException e) {e.printStackTrace();}}}, "C").start();new Thread(() -> {for (int i = 0; i < 10; i++) {try {airConditioner.decrement();} catch (InterruptedException e) {e.printStackTrace();}}}, "D").start();}
}class AirConditioner2 {  // 资源类private int number = 0;// 使用java8 lock 和 condition接口实现private Lock lock = new ReentrantLock();private Condition condition = lock.newCondition();public void increment() throws InterruptedException {lock.lock();try {// 1. 判断while (number != 0) {condition.await(); // this.wait();}// 2. 干活number++;System.out.println(Thread.currentThread().getName() + "\t" + number);// 3. 通知condition.signalAll(); // this.notifyAll();}catch (Exception e) {}finally {lock.unlock();}}public void decrement() throws InterruptedException {lock.lock();try {// 1. 判断while (number == 0) {condition.await(); // this.wait();}// 2. 干活number--;System.out.println(Thread.currentThread().getName() + "\t" + number);// 3. 通知condition.signalAll(); // this.notifyAll();}catch (Exception e) {}finally {lock.unlock();}}
}

码字不易,请大家多多指教~

这篇关于【多线程】线程间通信 之虚假唤醒和中断的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1130819

相关文章

Spring Boot3虚拟线程的使用步骤详解

《SpringBoot3虚拟线程的使用步骤详解》虚拟线程是Java19中引入的一个新特性,旨在通过简化线程管理来提升应用程序的并发性能,:本文主要介绍SpringBoot3虚拟线程的使用步骤,... 目录问题根源分析解决方案验证验证实验实验1:未启用keep-alive实验2:启用keep-alive扩展建

Java使用多线程处理未知任务数的方案介绍

《Java使用多线程处理未知任务数的方案介绍》这篇文章主要为大家详细介绍了Java如何使用多线程实现处理未知任务数,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 知道任务个数,你可以定义好线程数规则,生成线程数去跑代码说明:1.虚拟线程池:使用 Executors.newVir

Java终止正在运行的线程的三种方法

《Java终止正在运行的线程的三种方法》停止一个线程意味着在任务处理完任务之前停掉正在做的操作,也就是放弃当前的操作,停止一个线程可以用Thread.stop()方法,但最好不要用它,本文给大家介绍了... 目录前言1. 停止不了的线程2. 判断线程是否停止状态3. 能停止的线程–异常法4. 在沉睡中停止5

Linux中的进程间通信之匿名管道解读

《Linux中的进程间通信之匿名管道解读》:本文主要介绍Linux中的进程间通信之匿名管道解读,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、基本概念二、管道1、温故知新2、实现方式3、匿名管道(一)管道中的四种情况(二)管道的特性总结一、基本概念我们知道多

JAVA封装多线程实现的方式及原理

《JAVA封装多线程实现的方式及原理》:本文主要介绍Java中封装多线程的原理和常见方式,通过封装可以简化多线程的使用,提高安全性,并增强代码的可维护性和可扩展性,需要的朋友可以参考下... 目录前言一、封装的目标二、常见的封装方式及原理总结前言在 Java 中,封装多线程的原理主要围绕着将多线程相关的操

Java捕获ThreadPoolExecutor内部线程异常的四种方法

《Java捕获ThreadPoolExecutor内部线程异常的四种方法》这篇文章主要为大家详细介绍了Java捕获ThreadPoolExecutor内部线程异常的四种方法,文中的示例代码讲解详细,感... 目录方案 1方案 2方案 3方案 4结论方案 1使用 execute + try-catch 记录

linux本机进程间通信之UDS详解

《linux本机进程间通信之UDS详解》文章介绍了Unix域套接字(UDS)的使用方法,这是一种在同一台主机上不同进程间通信的方式,UDS支持三种套接字类型:SOCK_STREAM、SOCK_DGRA... 目录基础概念本机进程间通信socket实现AF_INET数据收发示意图AF_Unix数据收发流程图A

Spring Boot 中正确地在异步线程中使用 HttpServletRequest的方法

《SpringBoot中正确地在异步线程中使用HttpServletRequest的方法》文章讨论了在SpringBoot中如何在异步线程中正确使用HttpServletRequest的问题,... 目录前言一、问题的来源:为什么异步线程中无法访问 HttpServletRequest?1. 请求上下文与线

在 Spring Boot 中使用异步线程时的 HttpServletRequest 复用问题记录

《在SpringBoot中使用异步线程时的HttpServletRequest复用问题记录》文章讨论了在SpringBoot中使用异步线程时,由于HttpServletRequest复用导致... 目录一、问题描述:异步线程操作导致请求复用时 Cookie 解析失败1. 场景背景2. 问题根源二、问题详细分

Python中多线程和多进程的基本用法详解

《Python中多线程和多进程的基本用法详解》这篇文章介绍了Python中多线程和多进程的相关知识,包括并发编程的优势,多线程和多进程的概念、适用场景、示例代码,线程池和进程池的使用,以及如何选择合适... 目录引言一、并发编程的主要优势二、python的多线程(Threading)1. 什么是多线程?2.