• 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 }

    运行结果如下:

      

  • 相关阅读:
    魅族note手机 图片打马赛克
    魅蓝note手机一键root
    eclipse启动时return code 13
    Eclipse adt 23中运行百度地图官网上的demo出现fatal错误
    windows上部署svn服务器
    windows下jenkins slave 搭建
    图片懒加载
    tomcat7 设置静态资源的expires过期时间
    如何将不带www的根域名301重定向到带www的主域名
    简单的防止图片另存为
  • 原文地址:https://www.cnblogs.com/wang1001/p/9566711.html
Copyright © 2020-2023  润新知