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


推荐阅读