zoukankan      html  css  js  c++  java
  • 21.与重入锁相关联的Condition

    import java.util.concurrent.locks.Condition;
    import java.util.concurrent.locks.ReentrantLock;
    
    /**
     * 与重入锁相关联的Condition
     */
    public class ConditionDemo implements Runnable{
        public static ReentrantLock lock = new ReentrantLock();
        public static Condition condition = lock.newCondition();
        @Override
        public void run() {
            try {
                lock.lock();
                condition.await();//使当前线程等待,同时释放当前锁
                System.out.println("Thread is going on");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                lock.unlock();
            }
        }
        public static void main(String[] args) throws InterruptedException{
            ConditionDemo t = new ConditionDemo();
            Thread t1 = new Thread(t);
            t1.start();
            Thread.sleep(2000);
            //通知线程t1继续执行
            lock.lock();//调用signal()的方法时,线程要先获得相关的锁
            condition.signal();//唤醒一个在等待中的线程
            lock.unlock();//signal()调用后释放相关的锁给被唤醒的线程
        }
    }
    
  • 相关阅读:
    css定位
    题解 P2345 【奶牛集会】
    浅谈主席树
    浅谈Manacher算法
    CSP2019 游记
    P5025 [SNOI2017]炸弹
    浅谈2-SAT
    DAY 5模拟赛
    DAY 3
    Luogu P2915 [USACO08NOV]奶牛混合起来
  • 原文地址:https://www.cnblogs.com/fly-book/p/11388829.html
Copyright © 2011-2022 走看看