/*
下面的程序会出现下面的情况,当Thread-0, Thread-1, Thread-2都被wait的时候,可能会同时苏醒
Thread-0 put
Thread-1 put
Thread-2 put
Thread-3 get//在此处,Thread-3拿到锁之后,将所有的等待的线程唤醒,才有了下面的输出
Thread-2 put
Thread-1 put
Thread-0 put
*/ 虽然多个线程会同时苏醒,但是只有一个能获得cpu的执行权!
总之,同步中执行的只能是一个,但是存活的不一定就是一个! class DuckD{
public void put(){ synchronized(DuckD.class){ System.out.println(Thread.currentThread().getName()+" put");
try{
DuckD.class.wait();//Thread-0, Thread-1, Thread-2可能会同时在这里苏醒!
}catch(InterruptedException e){ }
//........
}
} public void get(){ synchronized(DuckD.class){ DuckD.class.notifyAll();
System.out.println(Thread.currentThread().getName()+" get");
try{
DuckD.class.wait();
}catch(InterruptedException e){ }
}
}
} class ProduceD implements Runnable{
DuckD dk;
ProduceD(DuckD dk){
this.dk=dk;
}
public void run(){
while(true)
dk.put();
}
} class ConsumeD implements Runnable{
DuckD dk;
ConsumeD(DuckD dk){
this.dk=dk;
}
public void run(){
while(true)
dk.get();
}
} class Test{
public static void main(String[] args){
DuckD dk=new DuckD();
Thread t1=new Thread(new ProduceD(dk));
Thread t2=new Thread(new ProduceD(dk));
Thread t3=new Thread(new ProduceD(dk));
Thread t4=new Thread(new ConsumeD(dk)); t1.start();
t2.start();
t3.start();
t4.start();
}
}

最新文章

  1. WCF 服务编程 - 常用绑定
  2. Swift - 进度条(UIProgressView)的用法
  3. oracle 资源学习汇总
  4. floyd算法
  5. O(1) 查询gcd
  6. spring jdbc分离数据库代码和java代码
  7. apache poi 生成excel
  8. 4分钟apache自带ab压力测试工具使用: 2015.10.4
  9. 转:Tomcat安装配置及站点说明
  10. C# explicit与implicit
  11. iOS - Swift 命令行输入输出
  12. POJ 3159 Candies(差分约束,最短路)
  13. Swift - 时间控制器NSTimer(每隔一定时间执行某个函数)
  14. Java learning notes (1):Basic Knowlege points
  15. nat的翻译类型(2)--动态nat
  16. 【java线程系列】java线程系列之线程间的交互wait()/notify()/notifyAll()及生产者与消费者模型
  17. DB2表被锁,如何解锁
  18. js中数组相关的Api
  19. html中引入调用另一个公用html模板文件的方法
  20. PHP函数之trigger_error

热门文章

  1. css块级元素,内联元素,内联块状元素
  2. zabbix_agentd.conf文件说明
  3. 备库Seconds_Behind_Master的计算
  4. 我的ORM之一 -- 查询
  5. ENode 1.0 - 框架的物理部署思路
  6. [.net 面向对象编程基础] (19) LINQ基础
  7. java算法(二)
  8. Linux Shell函数
  9. [译+改]最长回文子串(Longest Palindromic Substring) Part II
  10. 据说每个大牛、小牛都应该有自己的库——Ajax