通过 Demo 理解 Condition.await()、Condition.signal()的使用方法

public class ConditionDemo {
    private static final ReentrantLock lock = new ReentrantLock();
    private static final Condition condition = lock.newCondition();

    private static boolean flag = true;

    public static void main(String[] args) throws Exception {
        Thread waitThread = new Thread(new Waiter(), "Wait Thread");
        waitThread.start();
        Thread.sleep(1000);
        Thread notifyThread = new Thread(new Notifier(), "Notify Thread");
        notifyThread.start();
    }

    private static class Waiter implements Runnable {
        @Override
        public void run() {
            lock.lock();
            try {
                while (flag) {
                    System.out.println(Thread.currentThread() + " flag is true. wait @ " +
                            new SimpleDateFormat("HH:mm:ss").format(new Date()));
                    condition.await();
                }
                System.out.println(Thread.currentThread() + " flag is false. running @ " +
                        new SimpleDateFormat("HH:mm:ss").format(new Date()));
            } catch (InterruptedException e) {
                System.out.println(e.getMessage());
            } finally {
                lock.unlock();
            }
        }
    }

    private static class Notifier implements Runnable {
        @Override
        public void run() {
            lock.lock();
            try {
                System.out.println(Thread.currentThread() + " hold lock. notify @ " +
                        new SimpleDateFormat("HH:mm:ss").format(new Date()));

                condition.signalAll();

                flag = false;
                Thread.sleep(5000); // Thread.sleep() 不会释放锁

                System.out.println(Thread.currentThread() + " hold lock again. sleep @ " +
                        new SimpleDateFormat("HH:mm:ss").format(new Date()));
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                System.out.println(e.getMessage());
            } finally {
                lock.unlock();
            }

        }
    }
}

输出:

Thread[Wait Thread,5,main] flag is true. wait @ 15:25:39
Thread[Notify Thread,5,main] hold lock. notify @ 15:25:40
Thread[Notify Thread,5,main] hold lock again. sleep @ 15:25:45
Thread[Wait Thread,5,main] flag is false. running @ 15:25:50
join test

Process finished with exit code 0

和上一篇文章差不多,不过是把 Object 类型的对象 lock 换成了 Condition,使用方式也是相近的

Condition.await() 同样会释放锁

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值