java线程同步:使用Object的wait,notify,notifyAll做线程调度

2024-04-05 05:32

本文主要是介绍java线程同步:使用Object的wait,notify,notifyAll做线程调度,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

http://outofmemory.cn/java/java.util.concurrent/thread-sync-with-object-wait-notify-notifyAll

我们知道java中的所有类的祖先都是Object,Object类有四个个方法wait(),wait(long timeout),notify(),notifyAll(),这四个方法可以用来做线程的调度或者说是线程的同步控制。

  1. wait() 方法用来控制当前线程停止执行,等待其他线程对此Object实例调用notify或者notifyAll方法之后再继续执行
  2. wait(long timeout) 此方法的作用和wait()类似,但是增加了一个超时的设置,如果等待时间超过了timeout设定的毫秒数,那么当前线程会继续执行
  3. notify()方法从所有wait线程中选择一个线程,让它开始执行
  4. notifyAll()方法通知所有等待此对象的线程,开始执行

上面的解释字面意思上很容易理解,但是实际使用起来,却并不是那么简单,我们以一个实际的例子来看下如何使用这些方法。

假定我们有两个线程要打印1到9这9个数字,要求第一个线程打印1,2,3然后停止打印,由线程2打印4,5,6,然后线程2停止打印,通知线程1继续打印7,8,9.

需求很简单,我们可以建两个Runnable类,假定为PrinterA和PrinterB,先由PrinterB等待,由PrinterA打印1,2,3;PrinterA打印完之后通知PrinterB,然后自己进入等待状态;PrintB获得PrinterA的通知之后开始打印4、5、6,打印完毕之后需要通知PrinterA;然后PrinterA得到通知之后开始打印剩下的7、8、9。任务就完成了。

package cn.outofmemory.threading;public class WaitNotifyDemo {private volatile int val = 1;private synchronized void printAndIncrease() {System.out.println(Thread.currentThread().getName() + " prints " + val);val++;}// print 1,2,3 7,8,9public class PrinterA implements Runnable {@Overridepublic void run() {while (val <= 3) {printAndIncrease();}// print 1,2,3 then notify printerBsynchronized (WaitNotifyDemo.this) {System.out.println("PrinterA printed 1,2,3; notify PrinterB");WaitNotifyDemo.this.notify();}try {while (val <= 6) {synchronized (WaitNotifyDemo.this) {System.out.println("wait in printerA");WaitNotifyDemo.this.wait();}}System.out.println("wait end printerA");} catch (InterruptedException e) {e.printStackTrace();}while (val <= 9) {printAndIncrease();}System.out.println("PrinterA exits");}}// print 4,5,6 after printA print 1,2,3public class PrinterB implements Runnable {@Overridepublic void run() {while (val < 3) {synchronized (WaitNotifyDemo.this) {try {System.out.println("printerB wait for printerA printed 1,2,3");WaitNotifyDemo.this.wait();System.out.println("printerB waited for printerA printed 1,2,3");} catch (InterruptedException e) {e.printStackTrace();}}}while (val <= 6) {printAndIncrease();}System.out.println("notify in printerB");synchronized (WaitNotifyDemo.this) {WaitNotifyDemo.this.notify();}System.out.println("notify end printerB");System.out.println("PrinterB exits.");}}public static void main(String[] args) {WaitNotifyDemo demo = new WaitNotifyDemo();demo.doPrint();}private void doPrint() {PrinterA pa = new PrinterA();PrinterB pb = new PrinterB();Thread a = new Thread(pa);a.setName("printerA");Thread b = new Thread(pb);b.setName("printerB");// 必须让b线程先执行,否则b线程有可能得不到锁,执行不了wait,而a线程一直持有锁,会先notify了b.start();a.start();}
}

我们先把所有代码奉上了,你可以自己调试代码,在实际执行中来了解代码的实现机制。下面我们逐步分析下我们是如何控制两个线程调度的。

首先看main方法,在main方法中我们初始化了一个WaitNotifyDemo实例,然后调用了这个实例的doPrint方法。

在doPrint方法中我们使用PrinterA和PrinterB的实例初始化了两个线程,然后启动他们。

	private void doPrint() {PrinterA pa = new PrinterA();PrinterB pb = new PrinterB();Thread a = new Thread(pa);a.setName("printerA");Thread b = new Thread(pb);b.setName("printerB");// 必须让b线程先执行,否则b线程有可能得不到锁,执行不了wait,而a线程一直持有锁,会先notify了b.start();a.start();}

这里需要注意必须让b线程先执行,这样b线程才能先获得WaitNotifyDemo实例上的锁,并开始等待。在PrinterB的run方法中开始等待的代码片段如下:

                       while (val < 3) {synchronized (WaitNotifyDemo.this) {try {System.out.println("printerB wait for printerA printed 1,2,3");WaitNotifyDemo.this.wait();System.out.println("printerB waited for printerA printed 1,2,3");} catch (InterruptedException e) {e.printStackTrace();}}}

这里有一个while循环,如果val的值小于3,那么在WaitNotifyDemo的实例的同步块中调用WaitNotifyDemo.this.wait()方法,这里要注意无论是wait,还是notify,notifyAll方法都需要在其实例对象的同步块中执行,这样当前线程才能获得同步实例的同步控制权,如果不在同步块中执行wait或者notify方法会出现java.lang.IllegalMonitorStateException异常。另外还要注意在wait方法两边的同步块会在wait执行完毕之后释放对象锁。

这样PrinterB就进入了等待状态,我们再看下PrinterA的run方法:

                       while (val <= 3) {printAndIncrease();}// print 1,2,3 then notify printerBsynchronized (WaitNotifyDemo.this) {System.out.println("PrinterA printed 1,2,3; notify PrinterB");WaitNotifyDemo.this.notify();}try {while (val <= 6) {synchronized (WaitNotifyDemo.this) {System.out.println("wait in printerA");WaitNotifyDemo.this.wait();}}System.out.println("wait end printerA");} catch (InterruptedException e) {e.printStackTrace();}

这里首先打印了1、2、3,然后在同步块中调用了WaitNotifyDemo实例的notify方法,这样PrinterB就得到了继续执行的通知,然后PrinterA进入等待状态,等待PrinterB通知。

我们再看下PrinterB run方法剩下的代码:

			while (val <= 6) {printAndIncrease();}System.out.println("notify in printerB");synchronized (WaitNotifyDemo.this) {WaitNotifyDemo.this.notify();}System.out.println("notify end printerB");System.out.println("PrinterB exits.");

PrinterB首先打印了4、5、6,然后在同步块中调用了notify方法,通知PrinterA开始执行。

PrinterA得到通知后,停止等待,打印剩下的7、8、9三个数字,如下是PrinterA run方法中剩下的代码:

			while (val <= 9) {printAndIncrease();}

整个程序就分析完了,run下程序,控制台输出如下:

printerB wait for printerA printed 1,2,3
printerA prints 1
printerA prints 2
printerA prints 3
PrinterA printed 1,2,3; notify PrinterB
printerB waited for printerA printed 1,2,3
printerB prints 4
printerB prints 5
printerB prints 6
notify in printerB
notify end printerB
PrinterB exits.
wait end printerA
printerA prints 7
printerA prints 8
printerA prints 9
PrinterA exits

从输出内容上也可以看到wait,notify的执行过程。

在用wait,notify做线程同步是要特别注意下面两点:

  1. 不要选择字符串,Integer,Long,Type之类的对象做同步对象,因为这些类型在jvm中都有一些特殊的处理,有可能会有意想不到的情况。比如Integer,JVM对小于128的数字做了cache,如果你用Integer做同步对象的话,可能不同的逻辑锁定了相同的同步块。这类问题调试起来也不好调试,所以最好避免这样使用。
  2. 在调用obj.notify(),obj.wait方法时要在synchronized(obj)块中进行调用,否则会出现java.lang.IllegalMonitorStateException异常

这篇关于java线程同步:使用Object的wait,notify,notifyAll做线程调度的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Spring boot整合dubbo+zookeeper的详细过程

《Springboot整合dubbo+zookeeper的详细过程》本文讲解SpringBoot整合Dubbo与Zookeeper实现API、Provider、Consumer模式,包含依赖配置、... 目录Spring boot整合dubbo+zookeeper1.创建父工程2.父工程引入依赖3.创建ap

Linux线程之线程的创建、属性、回收、退出、取消方式

《Linux线程之线程的创建、属性、回收、退出、取消方式》文章总结了线程管理核心知识:线程号唯一、创建方式、属性设置(如分离状态与栈大小)、回收机制(join/detach)、退出方法(返回/pthr... 目录1. 线程号2. 线程的创建3. 线程属性4. 线程的回收5. 线程的退出6. 线程的取消7.

Linux下进程的CPU配置与线程绑定过程

《Linux下进程的CPU配置与线程绑定过程》本文介绍Linux系统中基于进程和线程的CPU配置方法,通过taskset命令和pthread库调整亲和力,将进程/线程绑定到特定CPU核心以优化资源分配... 目录1 基于进程的CPU配置1.1 对CPU亲和力的配置1.2 绑定进程到指定CPU核上运行2 基于

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

SpringBoot结合Docker进行容器化处理指南

《SpringBoot结合Docker进行容器化处理指南》在当今快速发展的软件工程领域,SpringBoot和Docker已经成为现代Java开发者的必备工具,本文将深入讲解如何将一个SpringBo... 目录前言一、为什么选择 Spring Bootjavascript + docker1. 快速部署与

深入理解Go语言中二维切片的使用

《深入理解Go语言中二维切片的使用》本文深入讲解了Go语言中二维切片的概念与应用,用于表示矩阵、表格等二维数据结构,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习吧... 目录引言二维切片的基本概念定义创建二维切片二维切片的操作访问元素修改元素遍历二维切片二维切片的动态调整追加行动态

Spring Boot spring-boot-maven-plugin 参数配置详解(最新推荐)

《SpringBootspring-boot-maven-plugin参数配置详解(最新推荐)》文章介绍了SpringBootMaven插件的5个核心目标(repackage、run、start... 目录一 spring-boot-maven-plugin 插件的5个Goals二 应用场景1 重新打包应用

prometheus如何使用pushgateway监控网路丢包

《prometheus如何使用pushgateway监控网路丢包》:本文主要介绍prometheus如何使用pushgateway监控网路丢包问题,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录监控网路丢包脚本数据图表总结监控网路丢包脚本[root@gtcq-gt-monitor-prome

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Spring Boot集成Druid实现数据源管理与监控的详细步骤

《SpringBoot集成Druid实现数据源管理与监控的详细步骤》本文介绍如何在SpringBoot项目中集成Druid数据库连接池,包括环境搭建、Maven依赖配置、SpringBoot配置文件... 目录1. 引言1.1 环境准备1.2 Druid介绍2. 配置Druid连接池3. 查看Druid监控