线程间的协作方式

2017-05-10  本文已影响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;

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

注意事项:

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实现生产者-消费者模型:

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()));
                }
            }
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读