线程间协作的两种方式

本文介绍了Java中线程间协作的两种方式:wait()、notify()、notifyAll()和Condition接口。wait/notify是Object类的方法,需要在同步块中调用,而Condition在Java 1.5后引入,提供了更加灵活的线程协作机制,如await()和signal()。文章通过示例展示了如何使用这两种方式实现生产者-消费者模型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


参考资料
线程间互相通信的过程,就是线程间的协作
Java中,线程协作的两种常见方式:

  • Object.wait(),Object.notify()
  • Condition
1 wait(),notify(),notifyAll

wait(),notify(),notifyAll() 是 Object类 中的 方法

public final native void notify();
public final native void notifyAll();
public final native void wait(long timeout) throws InterruptedException;
  • wait()、notify()和notifyAll()方法是本地方法,并且为final方法,无法被重写
  • 调用某个对象的wait()方法能让当前线程阻塞,并且当前线程必须拥有此对象的monitor(即锁)
  • 调用某个对象的notify()方法能够唤醒一个正在等待这个对象的monitor的线程,如果有多个线程都在等待这个对象的monitor,则只能唤醒其中一个线程
  • 调用notifyAll()方法能够唤醒所有正在等待这个对象的monitor的线程
  • 这 3个方法,必须在同步块或者同步方法中进行(synchronized块或者synchronized方法)

注意:

  1. notify()和notifyAll()方法只是唤醒等待该对象的monitor的线程,并 不决定哪个线程能够获取到monitor
  2. 一个线程被唤醒不代表立即获取了对象的monitor,只有等调用完notify()或者notifyAll()并 退出synchronized块释放对象锁 后,其余线程才可获得锁执行

示例:

public class MonitorTest {

    public static Object object = new Object();

    public static void main(String[] args) {
        Thread1 thread1 = new Thread1();
        Thread2 thread2 = new Thread2();

        thread1.start();

        try{
            Thread.sleep(200);
        } catch (InterruptedException e){
            e.printStackTrace();
        }

        thread2.start();

    }

    static class  Thread1 extends Thread{
        public void run(){
            synchronized (object){
                try{
                    object.wait();
                } catch (InterruptedException e){

                }
                System.out.println("线程"+ Thread.currentThread().getName()+"获取到锁");
            }
        }
    }

    static class Thread2 extends Thread {
        public void run() {
            synchronized (object) {
                object.notify();
                System.out.println("线程" + Thread.currentThread().getName() + "调用了object.notify()");
                System.out.println("线程"+Thread.currentThread().getName()+"释放了锁");
            }

        }

    }
}

运行结果:

线程Thread-1调用了object.notify()
线程Thread-1释放了锁
线程Thread-0获取到锁
2 Condition

Condition是在 java 1.5 中才出现的,它用来替代传统的 Object的wait()、notify() 实现线程间的协作,相比使用 Object的 wait()、notify(),使用 Conditionawait()signal() 这种方式实现线程间协作 更加安全和高效 。因此通常来说比较推荐使用 Condition,在阻塞队列那一篇博文中就讲述到了,阻塞队列实际上是使用了Condition来模拟线程间协作

  • Condition是个接口,基本的方法就是 await() 和 signal() 方法
  • Condition 依赖于Lock接口,生成一个Condition的基本代码是 lock.newCondition()
  • 调用 Condition 的 await() 和 signal() 方法,都必须在 lock保护之内,就是说必须在 lock.lock()lock.unlock() 之间才可以使用

Conditon中的await()对应Object的wait()
Condition中的signal()对应Object的notify()
Condition中的signalAll()对应Object的notifyAll()

3 生产者-消费者模型的实现
3.1 使用Object的wait()和notify()实现
public class ObjectProducerConsumerTest {

    private int queueSize = 10;
    private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(queueSize);

    public static void main(String[] args) {
        ObjectProducerConsumerTest test = new ObjectProducerConsumerTest();
        Producer producer = test.new Producer();
        Consumer consumer = test.new Consumer();

        producer.start();
        consumer.start();
    }

    class Consumer extends Thread {
        @Override
        public void run() {
            consume();
        }

        private void consume() {
            while (true) {
                synchronized (queue){
                    while (queue.size()==0){
                        try{
                            System.out.println("队列空,等待数据");
                            queue.wait();
                        } catch (InterruptedException e){
                            e.printStackTrace();
                            queue.notify();
                        }
                    }
                    queue.poll(); // 每次移走队首元素
                    queue.notify();
                    System.out.println("从队列取走一个元素,队列剩余\"+queue.size()+\"个元素");
                }
            }
        }
    }
    
    class Producer extends Thread{
        public void run(){
            produce();
        }

        private void produce() {
            while (true){
                synchronized (queue){
                    while (queue.size()== queueSize){
                        try{
                            System.out.println("队列满,等待有空余空间");
                            queue.wait();
                        } catch (InterruptedException e){
                            e.printStackTrace();
                            queue.notify();
                        }
                    }
                    queue.offer(1);  //每次插入一个元素
                    queue.notify();
                    System.out.println("向队列取中插入一个元素,队列剩余空间:"+(queueSize-queue.size()));
                }
            }
        }
    }

}
3.2 使用 Condition 实现
public class ConditionProducerConsumerTest {

    private int queueSize = 10;
    private PriorityQueue<Integer> queue = new PriorityQueue<Integer>(queueSize);

    private Lock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();

    public static void main(String[] args) {
        ConditionProducerConsumerTest test = new ConditionProducerConsumerTest();
        Producer producer = test.new Producer();
        Consumer consumer = test.new Consumer();

        producer.start();
        consumer.start();
    }
    
    class Consumer extends Thread{
        public void run(){
            consume();
        }

        private void consume() {
            while (true){
                lock.lock();
                try{
                    while (queue.size()==0){
                        try {
                            System.out.println("队列空,等待数据");
                            notEmpty.await();
                        } catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                    queue.poll();
                    notFull.signal();
                    System.out.println("从队列取走一个元素,队列剩余"+queue.size()+"个元素");
                } finally {
                    lock.unlock();
                }
            }
        }
    }

    class Producer extends Thread{
        public void run(){
            produce();
        }

        private void produce() {
            while (true){
                lock.lock();
                try{
                    while (queue.size() == queueSize){
                        try{
                            System.out.println("队列满,等待有空余空间");
                            notFull.await();
                        } catch (InterruptedException e){
                            e.printStackTrace();
                        }
                    }
                    queue.offer(1);
                    notEmpty.signal();
                    System.out.println("向队列取中插入一个元素,队列剩余空间:"+(queueSize-queue.size()));
                } finally {
                    lock.unlock();
                }
            }
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值