并发编程之Wait和Notify

简介: 我们把组成程序(Program)各个部分称为线程(Thread)。也可以说,线程就是程序中轻量级的进程(Process)。多线程(Multithreading)是Java的一个特性,它可以允许一个程序的多个部分(也就是线程)并发地执行,以达到最大程度利用CPU的目的。

Background

相关概念

什么是多线程

我们把组成程序(Program)各个部分称为线程(Thread)。也可以说,线程就是程序中轻量级的进程(Process)。

多线程(Multithreading)是Java的一个特性,它可以允许一个程序的多个部分(也就是线程)并发地执行,以达到最大程度利用CPU的目的。

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.

-- www.geeksforgeeks.org/multithread…

线程的状态

轮询

Samples

我们把循环执行某个逻辑判断,直到判断条件为true才执行判断体中的逻辑,叫做轮询(Polling)。轮询是会浪费一定的CPU资源的。

The process of testing a condition repeatedly till it becomes true is known as polling.Polling is usually implemented with the help of loops to check whether a particular condition is true or not. If it is true, certain action is taken. This waste many CPU cycles and makes the implementation inefficient.

-- www.geeksforgeeks.org/inter-threa…

下面提供一个轮询的实现示例。

Message:

isAvailable初始值是false,设置为true以后执行轮询体。

注意要使用线程安全的AtomicBoolean,如果使用boolean,在多线程情况下会有意想不到的结果。

import lombok.Getter;
import lombok.Setter;
import java.util.concurrent.atomic.AtomicBoolean;
@Setter
@Getter
public class Message {
    private AtomicBoolean isAvailable = new AtomicBoolean(false);
    private String msg;
    public Message(String str) {
        this.msg = str;
    }
}

PollingWaiter:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class PollingWaiter implements Runnable {
    private Message msg;
    public PollingWaiter(Message m) {
        this.msg = m;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        synchronized (msg) {
            int count = 0;
            System.out.println(name + " : waiter starting at time: " + LocalDateTime.now().format(DateTimeFormatter.ISO_TIME));
            while (!msg.getIsAvailable().get()) {
                count++;
            }
            System.out.println(name + " : msg is available at time: " + LocalDateTime.now().format(DateTimeFormatter.ISO_TIME));
            System.out.println(name + " : msg is available after count: " + count);
            System.out.println(name + " : processed: " + msg.getMsg());
        }
    }
}

执行测试:

休眠3秒以后,再执行轮询体内的代码。

import java.util.concurrent.atomic.AtomicBoolean;
public class WaitNotifyTest {
    public static void main(String[] args) {
        testPolling();
    }
    public static void testPolling() {
        Message msg = new Message("process it");
        PollingWaiter waiter = new PollingWaiter(msg);
        new Thread(waiter, "PollingWaiter").start();
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        msg.setIsAvailable(new AtomicBoolean(true));
        System.out.println("over");
    }
}

输出结果:

PollingWaiter : waiter starting at time: 14:26:08.482
over
PollingWaiter : msg is available at time: 14:26:11.402
PollingWaiter : msg is available after count: -69547606
PollingWaiter : processed: process it

wait 和 notify

除了轮询,Java通过wait 和 notify机制实现了线程间的通信。wait就是让执有某个对象的线程处于等待阻塞状态,而notify就是让等待阻塞中的线程重新获得CPU资源,再次进入运行状态。

由于wait 和 notify相关的方法实现在了java.lang.Object类中,因此所有的子类都可以使用这些方法。

wait 和 notify相关的方法需要在synchronized代码块中执行。

方法介绍

下面简要介绍一下这些方法:

  • wait()

wait()方法会导致当前线程从执行状态改为待执行状态,一直到另外一个线程为当前对象执行notify()或者notifyAll()方法。

  • wait(long timeout)

与wait()方法的不同点是,如果timeout时间到了以后,还没有前对象执行notify()或者notifyAll(),则线程自动开始执行。

值得注意的是执行wait(0)和wait()的效果是一样的。

  • wait(long timeout, int nanos)

与wait(long timeout)相比,此方法提供了等待超时设置的更高的精度,精确到了纳秒。

1毫秒 = 1,000,000 纳秒。

  • notify()

对于等待此对象的监视器的所有线程,执行notify()会随机唤醒一个线程。

  • notifyAll()

相比与notify(),此方法会唤醒所有等待该对象的监视器的线程。

示例

在上面示例代码的基础上,增加如下代码实现。

Waiter:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Waiter implements Runnable{
    private Message msg;
    public Waiter(Message m){
        this.msg=m;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        synchronized (msg) {
            try{
                System.out.println(name+" : waiting to get notified at time:"+ LocalDateTime.now().format(DateTimeFormatter.ISO_TIME));
                msg.wait();
            }catch(InterruptedException e){
                e.printStackTrace();
            }
            System.out.println(name+" : waiter thread got notified at time:"+LocalDateTime.now().format(DateTimeFormatter.ISO_TIME));
            //process the message now
            System.out.println(name+" : processed: "+msg.getMsg());
        }
    }
}

Notifier:

public class Notifier implements Runnable {
    private boolean isAll = true;
    private Message msg;
    public Notifier(Message msg, boolean isAll) {
        this.msg = msg;
        this.isAll = isAll;
    }
    @Override
    public void run() {
        String name = Thread.currentThread().getName();
        System.out.println(name + " started");
        try {
            Thread.sleep(3000);
            synchronized (msg) {
                System.out.println(name + " : got the msg : "+msg.getMsg());
                msg.setMsg(name + " : Notifier work done");
                if (isAll) {
                    msg.notifyAll();
                } else {
                    msg.notify();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

WaitNotifyTest:

import java.util.concurrent.atomic.AtomicBoolean;
public class WaitNotifyTest {
    public static void main(String[] args) {
        //testPolling();
        testNotify();
        //testNotifyAll();
    }
    public static void testPolling() {
        Message msg = new Message("process it");
        PollingWaiter waiter = new PollingWaiter(msg);
        new Thread(waiter, "PollingWaiter").start();
        try {
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        }
        msg.setIsAvailable(new AtomicBoolean(true));
        System.out.println("over");
    }
    public static void testNotify() {
        Message msg = new Message("process it");
        Waiter waiter1 = new Waiter(msg);
        new Thread(waiter1, "waiter1").start();
        Waiter waiter2 = new Waiter(msg);
        new Thread(waiter2, "waiter2").start();
        Notifier notifier = new Notifier(msg, false);
        new Thread(notifier, "notifier").start();
        System.out.println("All the threads are started");
    }
    public static void testNotifyAll() {
        Message msg = new Message("process it");
        Waiter waiter1 = new Waiter(msg);
        new Thread(waiter1, "waiter1").start();
        Waiter waiter2 = new Waiter(msg);
        new Thread(waiter2, "waiter2").start();
        Notifier notifier = new Notifier(msg, false);
        new Thread(notifier, "notifier").start();
        System.out.println("All the threads are started");
    }
}

在启动两个线程同时执行wait方法的时候,会发现notify以后只有一个线程被唤醒了,而另一个线程则陷入了无尽地等待之中。

Links

仓库地址

github.com/javastudyde…

参考链接

目录
相关文章
|
Web App开发 JavaScript Java
浏览器同域名请求的最大并发数限制
  当我们在浏览网页的时候,对浏览速度有一个重要的影响因素,就是浏览器的并发数量。并发数量简单通俗的讲就是,当浏览器网页的时候同时工作的进行数量。   如果同时只有2个并发连接数数量,那网页打开的时候只能依赖于这2条线程,前面如果有打开慢的内容,就会直接影响到后面的内容打开。
7260 0
|
11月前
|
存储 数据采集 弹性计算
面向多租户云的 IO 智能诊断:从异常发现到分钟级定位
当 iowait 暴涨、IO 延迟飙升时,你是否还在手忙脚乱翻日志?阿里云 IO 一键诊断基于动态阈值模型与智能采集机制,实现异常秒级感知、现场自动抓取、根因结构化输出,让每一次 IO 波动都有据可查,真正实现从“被动响应”到“主动洞察”的跃迁。
724 114
|
Prometheus 监控 Cloud Native
无痛入门Prometheus:一个强大的开源监控和告警系统,如何快速安装和使用?
Prometheus 是一个完全开源的系统监控和告警工具包,受 Google 内部 BorgMon 系统启发,自2012年由前 Google 工程师在 SoundCloud 开发以来,已被众多公司采用。它拥有活跃的开发者和用户社区,现为独立开源项目,并于2016年加入云原生计算基金会(CNCF)。Prometheus 的主要特点包括多维数据模型、灵活的查询语言 PromQL、不依赖分布式存储、通过 HTTP 拉取时间序列数据等。其架构简单且功能强大,支持多种图形和仪表盘展示模式。安装和使用 Prometheus 非常简便,可以通过 Docker 快速部署,并与 Grafana 等可
6655 3
|
机器学习/深度学习 人工智能 机器人
一周AI大事件
一周AI大事件
|
安全 数据库 数据安全/隐私保护
什么是 单点登录SSO?SSO工作原理
单点登录(SSO)让用户通过一组凭证访问多个应用,简化了多平台登录流程。在没有 SSO 的情况下,用户需为每个应用单独管理用户名和密码,而 SSO 通过身份提供商(IdP)和信任的服务提供商(SP)实现统一认证。这不仅减少了用户的密码管理负担,还降低了 IT 管理员的工作量,提高了安全性和用户体验。借助如 ADSelfService Plus 等工具,企业能更轻松地实施 SSO,并结合多重身份验证(MFA)增强安全性。
1415 9
|
测试技术
Valley2,基于电商场景的多模态大模型
Valley2是一种新颖的多模态大型语言模型,旨在通过可扩展的视觉-语言设计增强各个领域的性能,并拓展电子商务和短视频场景的实际应用边界。
949 3
|
人工智能 弹性计算 Kubernetes
【云故事探索】NO.10:厦门立马耀的数字化转型之路
厦门立马耀网络科技有限公司在数字化转型中,凭借敏锐的市场洞察和技术创新,将云计算深度融合于业务。其品牌“蝉妈妈”为中小企业提供全方位数字营销解决方案,成为行业标杆。面对快速变化的市场需求,公司通过与阿里云合作,构建高可靠性计算平台,提升效率,并利用AI技术赋能客户,推动业务多元化发展,展现了云计算在企业成长中的巨大潜力。
|
数据库
树的分类有哪些?
本文介绍了树的多种类型,包括二叉树、二叉搜索树、完全二叉树、AVL树、红黑树、B树和B+树,并解释了每种树的特点和用途。
1017 0
树的分类有哪些?
|
存储 算法 Java
手撕Java集合——链表
手撕Java集合——链表
|
存储 缓存 NoSQL
一文讲透 Redis 事务 (事务模式 VS Lua 脚本)
先说结论: Redis 的事务模式具备如下特点: - 保证隔离性; - 无法保证持久性; - 具备了一定的原子性,但不支持回滚; - 一致性的概念有分歧,假设在一致性的核心是约束的语意下,Redis 的事务可以保证一致性。 但 Lua 脚本更具备实用场景,它是另一种形式的事务,他具备一定的原子性,但脚本报错的情况下,事务并不会回滚。Lua 脚本可以保证隔离性,而且可以完美的支持**后面的步骤依赖前面步骤的结果**。
一文讲透 Redis 事务 (事务模式 VS Lua 脚本)

热门文章

最新文章