美文网首页程序员
Java - ReentrantLock和Condition的组

Java - ReentrantLock和Condition的组

作者: 夹胡碰 | 来源:发表于2020-12-30 00:27 被阅读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
    

    相关文章

      网友评论

        本文标题:Java - ReentrantLock和Condition的组

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