博客
关于我
求求你,别再用wait和notify了!
阅读量:459 次
发布时间:2019-03-06

本文共 5412 字,大约阅读时间需要 18 分钟。

为什么不能用 wait 和 notify 了?

在JDK 1.5中,Condition类被引入来替代wait和notify方法,这让很多开发者感到困惑。毕竟wait和notify是经典的线程通讯工具,似乎已经非常完美了。那么,为什么会推荐使用Condition而不是传统的wait和notify呢?让我来为你详细解答这个问题。

Condition 的优势

  • 避免线程“假死”

    notify方法在极端环境下可能会导致线程“假死”。这种情况通常发生在多个生产者和一个消费者的场景下。当一个生产者被唤醒后,它会通知所有等待的线程,包括其他生产者和消费者。假设消费者的任务尚未完成,其他生产者却被唤醒并进入等待状态,这样就会导致生产者的线程被意外地唤醒,进而引发程序的阻塞。

  • 性能更高

    Condition方法的性能比wait和notify更优。这是因为Condition实现了更高效的等待和唤醒机制,减少了不必要的线程操作,提高了程序的执行效率。

  • notify 线程“假死”的问题

    让我们通过经典的生产者和消费者模型来理解这一问题。

    正常版本

    在下面的代码中,使用wait和notify实现了生产者和消费者的交替工作:

    class Factory {    private int[] items = new int[1];    private int size = 0;    public synchronized void put() throws InterruptedException {        do {            while (size == items.length) {                System.out.println(Thread.currentThread().getName() + " 进入阻塞");                this.wait();                System.out.println(Thread.currentThread().getName() + " 被唤醒");            }            System.out.println(Thread.currentThread().getName() + " 开始工作");            items[0] = 1;            size++;            System.out.println(Thread.currentThread().getName() + " 完成工作");            this.notify();        } while (true);    }    public synchronized void take() throws InterruptedException {        do {            while (size == 0) {                System.out.println(Thread.currentThread().getName() + " 进入阻塞(消费者)");                this.wait();                System.out.println(Thread.currentThread().getName() + " 被唤醒(消费者)");            }            System.out.println("消费者工作~");            size--;            this.notify();        } while (true);    }}public class NotifyDemo {    public static void main(String[] args) {        Factory factory = new Factory();        Thread producer = new Thread(() -> {            try {                factory.put();            } catch (InterruptedException e) {                e.printStackTrace();            }        }, "生产者");        producer.start();        Thread consumer = new Thread(() -> {            try {                factory.take();            } catch (InterruptedException e) {                e.printStackTrace();            }        }, "消费者");        consumer.start();    }}

    线程假死版本

    当我们增加两个生产者时,就会遇到线程假死的问题:

    public class NotifyDemo {    public static void main(String[] args) {        Factory factory = new Factory();        Thread producer = new Thread(() -> {            try {                factory.put();            } catch (InterruptedException e) {                e.printStackTrace();            }        }, "生产者");        producer.start();        Thread producer2 = new Thread(() -> {            try {                factory.put();            } catch (InterruptedException e) {                e.printStackTrace();            }        }, "生产者2");        producer2.start();        Thread consumer = new Thread(() -> {            try {                factory.take();            } catch (InterruptedException e) {                e.printStackTrace();            }        }, "消费者");        consumer.start();    }}

    在这个版本中,生产者2在没有数据时被唤醒,导致线程假死,整个程序无法继续执行。

    使用 Condition

    为了避免线程假死问题,我们可以使用Condition类。Condition类提供了更灵活的等待和唤醒机制,可以避免不必要的线程唤醒。

    使用 Condition 的代码示例

    class FactoryByCondition {    private int[] items = new int[1];    private int size = 0;    private Lock lock = new ReentrantLock();    private Condition producerCondition = lock.newCondition();    private Condition consumerCondition = lock.newCondition();    public void put() throws InterruptedException {        do {            lock.lock();            while (size == items.length) {                System.out.println(Thread.currentThread().getName() + " 进入阻塞");                producerCondition.await();                System.out.println(Thread.currentThread().getName() + " 被唤醒");            }            System.out.println(Thread.currentThread().getName() + " 开始工作");            items[0] = 1;            size++;            System.out.println(Thread.currentThread().getName() + " 完成工作");            consumerCondition.signal();        } while (true);    }    public void take() throws InterruptedException {        do {            lock.lock();            while (size == 0) {                System.out.println(Thread.currentThread().getName() + " 进入阻塞(消费者)");                consumerCondition.await();            }            System.out.println("消费者工作~");            size--;            producerCondition.signal();        } while (true);    }}

    多线程测试

    public class NotifyDemo {    public static void main(String[] args) {        FactoryByCondition factory = new FactoryByCondition();        Thread producer = new Thread(() -> {            try {                factory.put();            } catch (InterruptedException e) {                e.printStackTrace();            }        }, "生产者");        producer.start();        Thread producer2 = new Thread(() -> {            try {                factory.put();            } catch (InterruptedException e) {                e.printStackTrace();            }        }, "生产者2");        producer2.start();        Thread consumer = new Thread(() -> {            try {                factory.take();            } catch (InterruptedException e) {                e.printStackTrace();            }        }, "消费者");        consumer.start();    }}

    性能对比

    如果我们使用 notifyAll 替代 notify,虽然可以避免线程假死,但会带来性能问题。因为 notifyAll 会唤醒所有等待的线程,包括无需执行任务的生产者,导致资源浪费。

    总结

    Condition类提供了一种更安全和高效的线程通讯方式,避免了wait和notify方法的潜在问题。如果你正在进行并发编程,尤其是在涉及多个生产者和消费者的场景中,使用Condition类是更好的选择。

    转载地址:http://ewwbz.baihongyu.com/

    你可能感兴趣的文章
    Node-RED中实现HTML表单提交和获取提交的内容
    查看>>
    node.js 怎么新建一个站点端口
    查看>>
    Node.js 文件系统的各种用法和常见场景
    查看>>
    node.js 配置首页打开页面
    查看>>
    node.js+react写的一个登录注册 demo测试
    查看>>
    Node.js中环境变量process.env详解
    查看>>
    Node.js安装与配置指南:轻松启航您的JavaScript服务器之旅
    查看>>
    Node.js的循环与异步问题
    查看>>
    nodejs libararies
    查看>>
    nodejs 运行CMD命令
    查看>>
    nodejs-mime类型
    查看>>
    nodejs中Express 路由统一设置缓存的小技巧
    查看>>
    NodeJs学习笔记001--npm换源
    查看>>
    Node入门之创建第一个HelloNode
    查看>>
    Node出错导致运行崩溃的解决方案
    查看>>
    Node提示:error code Z_BUF_ERROR,error error -5,error zlib:unexpected end of file
    查看>>
    NOIp2005 过河
    查看>>
    NOPI读取Excel
    查看>>
    NoSQL&MongoDB
    查看>>
    NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
    查看>>