java经典面试题:子线程先运行30次主线程,主线程40次,如此循环50次
这不就是两个线程交替执行么?用两个 BlockingQueue 就搞定了。
■网友public class BizTest { public static void main(String args) throws Exception{ for(int i=0;i\u0026lt;5;i++){ Thread sub = new Thread(new Biz()); sub.start(); sub.join(); for(int x=0;x\u0026lt;5;x++) System.out.println("main thread says:" + x); } }}class Biz implements Runnable{ public void run() { for(int x=0;x\u0026lt;5;x++) System.out.println("sub thread says:" + x); }}针对你的程序改版如下:public class BizTest { static final Biz biz = new Biz(); public static void main(String args) throws Exception{ Thread father = new Thread(new Runnable() { public void run() { biz.sonDo(); } }).start(); Thread son = new Thread(new Runnable() { public void run() { biz.fatherDo(); } }).start(); }}class Biz { int cyc = 1; public void sonDo() { synchronized (this){ try{ while(cyc\u0026lt;11){ if(cyc%2==1){ //如果cyc为单数,则运行son作业,否则直接交锁 cyc++; //1,3,5,6,9 执行5次 for(int x=0;x\u0026lt;5;x++) System.out.println("son thread says:" + x); } this.notifyAll(); this.wait(); } }catch (Exception e){ e.printStackTrace(); } } } public void fatherDo(){ synchronized (this){ try{ while(cyc\u0026lt;11){ if(cyc%2==0){ //如果是cyc为双数,则运行father作业,否则交锁 cyc++; //2,4,6,8,10 执行5次 for(int x=0;x\u0026lt;5;x++) System.out.println("father thread says:" + x); } this.notifyAll(); this.wait(); } }catch (Exception e){ e.printStackTrace(); } } }}
■网友
要用wait和notify就老实当作condition variable用就好了, 照着正统用法写就行了public class Test {\tpublic static void main(String args) throws InterruptedException {\t\tfinal Business business = new Business();\t\t// 子线程\t\tThread t1 = new Thread(new Runnable() {\t\t\t@Override\t\t\tpublic void run() { for (int i = 0; i \u0026lt; 50; i++) { try { business.sonBusiness(i); } catch (InterruptedException e) { } }\t\t\t}\t\t}); t1.start(); Thread t2 = new Thread(new Runnable() { @Override public void run() { for (int i = 0; i \u0026lt; 50; i++) { try { business.mainBusiness(i); } catch (InterruptedException e) { } } } }); t2.start(); t1.join(); t2.join();\t}}class Business { private int pos = 1;\tpublic void mainBusiness(int i) throws InterruptedException { synchronized (this) { while (pos != 2) { this.wait(); } } for (int j = 1; j \u0026lt;= 20; j++) { System.out.println("主线程第" + i + "轮,第" + j + "次"); } synchronized (this) { pos = 1; this.notify(); }\t}\tpublic void sonBusiness(int i) throws InterruptedException { synchronized (this) { while (pos != 1) { this.wait(); } } for (int j = 1; j \u0026lt;= 30; j++) { System.err.println("子线程第" + i + "轮,第" + j + "次"); } synchronized (this) { pos = 2; this.notify(); }\t}}
推荐阅读
- 尹相杰|尹相杰走穴捞金,舞台简陋显落魄,换搭档再唱经典反被调侃
- dart这编程语言现在发展怎么样了,语法与Java,c#很相似,甚至更简洁
- Java工程师和C++工程师在工作上有啥区别哪个更适合自身发展
- 汽车|体验一辆40多岁的经典Mini:一边被虐一边喊爽
- My车轱辘|激进与经典的博弈!起亚智跑ACE和日产逍客谁更好?
- 面诊|
- 环球车讯网|经典之作 劳斯莱斯库里南SUV详解
- 27岁,转行java的血与泪,该何去何从
- 怎样统计工程中未使用的java类
- 新互联网网站用Java还靠谱么对比Php,Python,Ruby的话
