练习题之Wait/Notify
2016-05-17 23:10
465 查看
方案一:
方案二:
public class PrintABC { public static void main(String[] args) { AtomicInteger synObj = new AtomicInteger(0); Runnable r = new ThreadModel(synObj); new Thread(r,"A").start(); new Thread(r,"B").start(); new Thread(r,"C").start(); } } public class ThreadModel implements Runnable { public volatile AtomicInteger ato; public ThreadModel(AtomicInteger ato) { this.ato = ato; } public void run() { for(int i=0;i<10;i++) { synchronized(ato) { if(ato.get()%3==0) { System.out.println("A); ato.set(ato.get()+1); ato.notifyAll(); } else if(ato.get()%3==1) { System.out.println("B); ato.set(ato.get()+1); ato.notifyAll(); } else if(ato.get()%3==2) { System.out.println("C); ato.set(ato.get()+1); ato.notifyAll(); } else { ato.wait(); } } } } }
方案二:
public class printABC { public static void main(String [] args) { AtomicInteger ato = new AtomicInteger(0); ThreadModel modelA = new ThreadModel(ato,"A",0); ThreadModel modelB = new ThreadModel(ato,"B",0); ThreadModel modelC = new ThreadModel(ato,"C",0); new Thread(modelA).start(); new Thread(modelB).start(); new Thread(modelC).start(); } } public class ThreadModel { private AtomicInteger ato; private String printChar; private int flag; private int count = 0; public ThreadModel(AtomicInteger ato,String printChar,int flag) { this.ato = ato; this.printChar = printChar; this.flag = flag; } public void run() { synchronized(ato) { while(true) { if(ato.get()%3==flag) { System.out.println(printChar); ato.set(ato.get()+1); ato.notifyAll(); count++; if(count==10) { break; } }else { ato.wait(); } } } } }
相关文章推荐
- POJ 2110 Mountain Walking(二分+BFS)
- UVA 10976 Fractions Again?! (暴力预处理)
- 什么是RAID? 硬RAID 和软RAID的区别是什么?
- Main函数中的argc和argv应用举例
- codeforces 675B Restoring Painting
- HDU 1022 Train Problem I (STL 栈模拟)
- Codeforces Round #353 (Div. 2) B. Restoring Painting __ map or set 、思维题
- mysql-创建用户报错ERROR 1396 (HY000): Operation CREATE USER failed for 'XXXX'@'XXXX'
- 未来10年最可能出现颠覆性创新的9大领域,第一条就属于我们
- Unable to connect to a repository at URL '': authorization failed: Could not authenticate to server:
- fail-fast机制
- Could not find a storyboard named 'Main' in bundle NSBundle
- VS2010 LINK1123:failure during conversion to COFF:file invalid or corrupt
- main中的运行时(runtime)
- Understand images & containers
- Codeforces Round #353 (Div. 2) B. Restoring Painting(方块内放数,问有多少种不同的放法)
- svn cleanup failed–previous operation has not finished
- codeforces 675B B. Restoring Painting(暴力枚举)
- hmailserver和rounduce安装
- TNS-00510 IBM/AIX RISC System/6000 Error: 11: Resource temporarily unavailable