java并发编程(3)--传统方式线程之间的通信

来源:互联网 发布:域名交易平台源码 编辑:程序博客网 时间:2024/05/22 06:55

1,子线程循环10次 主线程循环100次 如此交替 50次

package com.qunar.thread;/** * 子线程循环10次 主线程循环100次 如此交替 50次 * @author hao.su * */public class TranditionalThreadCommunication {public static void main(String[] args) {final Business business = new Business();new Thread(new Runnable() {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{boolean bShouldSub = true;public synchronized void sub(int i){while(!bShouldSub){//用while防止未唤醒try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}for(int j = 0;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 = 0;j<100;j++){System.out.println("main thread sequence of"+j+",loop of"+i);}bShouldSub = true;this.notify();}}

要用到的共同数据 包括同步锁,或共同算法的若干个方法应该归在同一个类上,这样良好的体现了面向对象编程,也体现了高内聚的特征

同步锁要放在资源类中,不是放在线程上

在Business中 使用while来确保条件是不是真的满足了,这样可以防止伪唤醒

在java文档中有如下解释:

对于某一个参数的版本,实现中断和虚假唤醒是可能的,而且此方法应始终在循环中使用:

synchronized (obj) {while (<condition does not hold>)obj.wait();... // Perform action appropriate to condition     }



0 0