博客
关于我
求求你,别再用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/

    你可能感兴趣的文章
    OAuth2:项目演示-模拟微信授权登录京东
    查看>>
    OA系统多少钱?OA办公系统中的价格选型
    查看>>
    OA系统选型:选择好的工作流引擎
    查看>>
    OA项目之我的会议(会议排座&送审)
    查看>>
    OA项目之我的会议(查询)
    查看>>
    Object c将一个double值转换为时间格式
    查看>>
    object detection训练自己数据
    查看>>
    object detection错误Message type "object_detection.protos.SsdFeatureExtractor" has no field named "bat
    查看>>
    object detection错误之Could not create cudnn handle: CUDNN_STATUS_INTERNAL_ERROR
    查看>>
    object detection错误之no module named nets
    查看>>
    Object of type 'ndarray' is not JSON serializable
    查看>>
    Object Oriented Programming in JavaScript
    查看>>
    object references an unsaved transient instance - save the transient instance before flushing
    查看>>
    Object.keys()的详解和用法
    查看>>
    OBJECTIVE C (XCODE) 绘图功能简介(转载)
    查看>>
    Objective-C ---JSON 解析 和 KVC
    查看>>
    Objective-C 编码规范
    查看>>
    Objective-C——判断对象等同性
    查看>>
    Objective-C之成魔之路【7-类、对象和方法】
    查看>>
    Objective-C享元模式(Flyweight)
    查看>>