子线程业务:循环10次
主线程业务:循环20次
这两个循环(业务)需要交替执行共50次
要用到共同数据的(包括同步锁)或共同算法(加密解密)的若干个方法应该归在同一个类上,这种设计正好体现了高内聚和程序的健壮性
while (bShouldSub) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } }
中使用while防止假唤醒,使用if就不行
虚假唤醒就是一些obj.wait()会在除了obj.notify()和obj.notifyAll()的其他情况被唤醒,而此时是不应该返回的,所以要加条件判断。
synchronized (obj) { while (<condition does not hold>) obj.wait(); ... // Perform action appropriate to condition }
public class TraditionalThreadCommunication { final Business business = new Business(); public static void main(String[] args) { new TraditionalThreadCommunication().init(); } private void init() { new Thread(new Runnable() { @Override public void run() { for (int i = 0; i <= 50; i++) { business.sub(i); } } }).start(); for (int i = 0; i <= 50; i++) { business.main(i); } } //业务对象 class Business { private boolean bShouldSub = true; public synchronized void sub(int i) { while (!bShouldSub) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 10; j++) { System.out.println("sub thread sequence of" + j + ",loop of " + i); } bShouldSub = false; this.notify(); } public synchronized void main(int i) { while (bShouldSub) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int j = 1; j <= 20; j++) { System.out.println("main thread sequence of" + j + ",loop of " + i); } bShouldSub = true; this.notify(); } } }
使用lock和condition改写代码
http://tianxingzhe.blog.51cto.com/3390077/1716805
本文出自 “点滴积累” 博客,请务必保留此出处http://tianxingzhe.blog.51cto.com/3390077/1716473