美文网首页
线程间的协作方式

线程间的协作方式

作者: 大海孤了岛 | 来源:发表于2017-05-10 14:14 被阅读32次

转自:线程间协作的两种方式:wait、notify、notifyAll和Condition

wait()、notify()和notifyAll()

wait()、notify()和notifyAll()是Object类中的方法:

/**
 * Wakes up a single thread that is waiting on this object's
 * monitor. If any threads are waiting on this object, one of them
 * is chosen to be awakened. The choice is arbitrary and occurs at
 * the discretion of the implementation. A thread waits on an object's
 * monitor by calling one of the wait methods
 */
public final native void notify();
 
/**
 * Wakes up all threads that are waiting on this object's monitor. A
 * thread waits on an object's monitor by calling one of the
 * wait methods.
 */
public final native void notifyAll();
 
/**
 * Causes the current thread to wait until either another thread invokes the
 * {@link java.lang.Object#notify()} method or the
 * {@link java.lang.Object#notifyAll()} method for this object, or a
 * specified amount of time has elapsed.
 * <p>
 * The current thread must own this object's monitor.
 */
public final native void wait(long timeout) throws InterruptedException;

从上面的三个方法中,可以获取到如下信息:

  • wait()、notify()和notifyAll()方法都是本地方法,并且为final类型,无法被重写。
  • 调用某个对象的wait()方法能让当前线程阻塞,并且当前线程必须拥有此对象的monitor(即锁)。
  • 调用某个对象的notify()方法能够唤醒一个正在等待这个对象的monitor的线程,如果有多个线程都在等待这个对象的monitor,则只能唤醒其中一个线程。
  • 调用notifyAll()方法能够唤醒所有正在等待这个对象的monitor的线程。

注意事项:

  • 以上三种方法都必须在同步方法或者同步方法块中进行。
  • Thread.sleep()方法只是让当前线程暂停执行一段时间,从而让其他线程有机会继续执行,但它并不释放对象锁。
  • wait()方法是相当于当前线程交出此对象的monitor,然后进入等待状态,然后后续再次获得此对象的锁。
  • notify()和notifyAll()方法是去唤醒等待该对象的线程,去获取对象的monitor。
  • 尤为注意的一点是,一个线程被唤醒不代表立即获取了对象的monitor,只有等调用完了notify或者notifyAll()并退出同步代码块,释放对象锁后,其余线程才可获得执行。
public class ThreadTest {

    public static Object object = new Object();
    public static void main(String[] args) throws InterruptedException {
        Thread1 t1 = new Thread1();
        Thread2 t2 = new Thread2();
        t1.start();
        //确保线程1先开始运行
        Thread.sleep(1000);
        t2.start();
    }

    static class Thread1 extends Thread{
        @Override
        public void run() {
            synchronized (object){
                try {
                    //交出对象的monitor,进入等待状态
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("线程" + Thread.currentThread().getName() + "获取到了锁");
            }
        }
    }

    static class Thread2 extends Thread{
        @Override
        public void run() {
            synchronized (object){
                //唤醒线程去获取对象的monitor,但这时候并没有获取到锁
                object.notify();
                System.out.println("线程" + Thread.currentThread().getName() + "调用了object.notify()方法");
                System.out.println("线程" + Thread.currentThread().getName() + "释放了锁");
            }
        }
    }

}
输出结果:
线程Thread-1调用了object.notify()方法
线程Thread-1释放了锁
线程Thread-0获取到了锁

Condition

  • Condition是个接口,基本的方法是await()和signal()方法;
  • Condition依赖于Lock接口,生成一个Condition的基本代码是lock.newCondition();
  • 调用Condition的await()和signal()方法,都必须在lock保护之内,也就是说必须在lock.lock()和lock.unlock()之间才可以使用;
  • Condition中的await、signal和signalAll方法与Object中的wait、notify和notifyAll是一一对应的。

使用Condition实现生产者-消费者模型:

public class ConditionDemo {
    private int queueSize = 10;
    private PriorityQueue<Integer> queue = new PriorityQueue<>(queueSize);
    private Lock lock = new ReentrantLock();
    private Condition notFull = lock.newCondition();
    private Condition notEmpty = lock.newCondition();

    public static void main(String[] args) {
        ConditionDemo demo = new ConditionDemo();
        ConditionDemo.Consumer consumer = demo.new Consumer();
        ConditionDemo.Producer producer = demo.new Producer();
        consumer.start();
        producer.start();
    }

    class Consumer extends Thread {
        @Override
        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 {
        @Override
        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();
                }
            }
        }
    }
}

使用wait()和notify()来实现生产者-消费者模型:

public class ObjectDemo {
    private int queueSize = 10;
    private PriorityQueue<Integer> queue = new PriorityQueue<>(queueSize);

    public static void main(String[] args){
        ObjectDemo demo = new ObjectDemo();
        ObjectDemo.Consumer consumer = demo.new Consumer();
        ObjectDemo.Producer producer = demo.new Producer();
        consumer.start();
        producer.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{
        @Override
        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()));
                }
            }
        }
    }
}

相关文章

  • JAVA高并发(四)

    线程间的协作: 多线程的世界线程并不孤立,线程间常见的协作方式以及java提供的支持: 最为经典的便是Obje...

  • 线程间的协作方式

    转自:线程间协作的两种方式:wait、notify、notifyAll和Condition wait()、noti...

  • JAVA并发梳理(三) 多线程协作方式及实现原理

    线程间的基本协作方式请参考 多线程协作方式。在此基础上,结合源码梳理一下每种方式的实现原理。 Synchroniz...

  • java并发之线程协作

    在多线程开发中,常常在线程间进行切换或调度,那么就会出现线程协作。线程协作有几种方式如下: 阻塞/唤醒 让步 取消...

  • 线程间的通信

    线程间的通信方式: 数据交互: 文件共享网络共享共享变量 线程间协作: jdk提供的线程协调API,例如:susp...

  • 线程间协作

    join() 在线程中调用另一个线程的 join() 方法,会将当前线程挂起,直到目标线程结束。 执行结果 wai...

  • JAVA多线程11-基础篇-线程间通讯wait,notify

    本章介绍 线程间的协作方式,主要包含wait(),notify(),notifyAll()方法的使用以及代码示例 ...

  • Java线程通信

    线程通信 线程通信指的是多个线程在运行的期间,相互之间的数据交互协作。 1.通信方式 实现多个线程直接的协作,涉及...

  • 多线程协作方式

    同步控制是并发程序必不可少的重要手段。JDK提供了很多多线程控制方法。 内部锁Synchronized 重入锁Re...

  • 线程的等待与通知,如何使用Condition实现?

    线程的等待与通知,目的就是为了实现线程间的协作,那一般情况下,我们最容易想到的方式是使用循环以及公共变量,比如: ...

网友评论

      本文标题:线程间的协作方式

      本文链接:https://www.haomeiwen.com/subject/dqnwtxtx.html