程序员

Java - ReentrantLock和Condition的组

2020-12-30  本文已影响0人  夹胡碰

Condition的作用用一句话概括就是为了实现线程的等待(await)和唤醒(signal),ReentrantLock+Condition的组合使用相当于synchronized+Object.wait/notify

1. 使用

public class ConditionTest {

    public static ReentrantLock reentrantLock = new ReentrantLock();
    public static Condition condition = reentrantLock.newCondition();

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new MyThread0());
        thread.start();

        Thread.sleep(2000);
        reentrantLock.lock();
        System.out.println("main lock");
        condition.signal();
        System.out.println("main signalAll unlock");
        reentrantLock.unlock();

    }

    public static class MyThread0 implements Runnable{

        @Override
        public void run() {
            reentrantLock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " await");
                condition.await(); // 挂起线程并释放锁
                System.out.println(Thread.currentThread().getName() + " await end");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
out => 
Thread-0 await
main lock
main signalAll unlock
Thread-0 await end
上一篇 下一篇

猜你喜欢

热点阅读