zoukankan      html  css  js  c++  java
  • Condition实现等待、通知

    使用Condition实现等待/通知:

     1 import java.util.concurrent.locks.Condition;
     2 import java.util.concurrent.locks.Lock;
     3 import java.util.concurrent.locks.ReentrantLock;
     4 
     5 
     6 public class MyService {
     7     
     8     private Lock lock = new ReentrantLock();
     9     private Condition condition = lock.newCondition();
    10     
    11     public void await() {
    12         try {
    13             lock.lock();//上锁
    14             System.out.println("await时间为:" + System.currentTimeMillis());
    15             condition.await();
    16         } catch (InterruptedException e) {
    17             e.printStackTrace();
    18         }finally {
    19             lock.unlock();
    20         }
    21     }
    22     
    23     public void signal() {
    24         try {
    25             lock.lock();
    26             System.out.println("signal时间为:" + System.currentTimeMillis());
    27             condition.signal();
             System.out.println("我被唤醒了");
    28 } catch (Exception e) { 29 e.printStackTrace(); 30 }finally { 31 lock.unlock(); 32 } 33 } 34 }
     1 public class ThreadA extends Thread{
     2 
     3     private MyService service;
     4     
     5     public ThreadA(MyService service) {
     6         this.service = service;
     7     }
     8     
     9     @Override
    10     public void run() {
    11         service.await();
    12     }
    13 }
     1 /**
     2  *    测试类
     3  */
     4 public class Run {
     5 
     6     /**
     7      *    Object类中的wait() 相当于Condition类中的await()
     8      *    Object类中的wait(long timeout) 相当于Condition类中的await(long time,TimeUnit unit)
     9      *    Object类中的notify() 相当于Condition类中的signal()
    10      *    Object类中的notifyAll() 相当于Condition类中的signalAll()
    11      */
    12     public static void main(String[] args) {
    13         MyService service = new MyService();
    14         
    15         ThreadA a = new ThreadA(service);
    16         a.start();
    17         try {
    18             Thread.sleep(3000);
    19         } catch (InterruptedException e) {
    20             e.printStackTrace();
    21         }
    22         service.signal();
    23     }
    24 }

    运行结果如下:

      

  • 相关阅读:
    PAT 甲级 1132 Cut Integer (20 分)
    AcWing 7.混合背包问题
    AcWing 9. 分组背包问题
    AcWing 5. 多重背包问题 II
    AcWing 3. 完全背包问题
    AcWing 4. 多重背包问题
    AcWing 2. 01背包问题
    AcWing 875. 快速幂
    AcWing 874. 筛法求欧拉函数
    AcWing 873. 欧拉函数
  • 原文地址:https://www.cnblogs.com/wang1001/p/9566711.html
Copyright © 2011-2022 走看看