java并发相关

显示锁 Condition

2018-10-25  本文已影响8人  韭菜待收割

1、Object提供的等待通知方法

public class MainTest {

    private static volatile int condition = 0;
    private static final Object object = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (object) {
                    while (condition != 1) {
                        try {
                            object.wait();
                        } catch (InterruptedException e) {
                            Thread.currentThread().interrupt();
                        }
                    }
                    System.out.println("线程执行完毕");
                }
            }
        });
        thread.start();
        Thread.sleep(2000);
        condition = 1;
        synchronized (object) {
            object.notify();
        }
    }

}

2、显示锁提供的等待通知

public class MainTest {

    private static volatile int condition = 0;
    private static ReentrantLock reentrantLock = new ReentrantLock();
    private static Condition lockCondition = reentrantLock.newCondition();

    public static void main(String[] args) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                reentrantLock.lock();
                try {
                    while (condition != 1) {
                        //lockCondition.wait();//不是下面这个玩意
                        
                        //必须要获取到锁,不然报错;
                        //和对象的wait()必须在同步块中使用一个道理
                        lockCondition.await();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    reentrantLock.unlock();
                }

                System.out.println("线程执行完毕");
            }
        });
        thread.start();
        condition = 1;
        reentrantLock.lock();
        try {
            Thread.sleep(2000);
            lockCondition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            reentrantLock.unlock();
        }
    }

}

3、区别

lock.newCondition() 获取多个Condition对象。
在一个lock对象上,可以有多个等待队列。
而Object的等待通知只有一个等待队列。

4、源码

Condition.await()会构造一个新的等待队列节点加入到等待队列队尾。
Condition.signal()会通知等待队列队首的节点,将节点加入同步队列。

见源码

Condition源码分析

上一篇下一篇

猜你喜欢

热点阅读