日出星辰

线程学习笔记【4】---线程之间通信

子线程先循环10次,然后主线程循环100次,再子线程循环10次,主线程循环100次,就这样循环往复50次。

public class Communtion01 {

public static void main(String args[]) {
final Bussiness buss = new Bussiness();
new Thread(new Runnable() {

public void run() {
for (int j = 1; j <= 50; j++) {
buss.sub(j);
}
}
}).start();

for (int j = 1; j <= 50; j++) {
buss.main(j);
}
}

}

class Bussiness {
private boolean subFlag = true;

//Cpu照顾sub线程,执行到sub(),但还不该sub执行,那就wait
public synchronized void sub(int j) {
while (!subFlag) {
try {
this.wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i = 1; i <= 10; i++) {
System.out.println(Thread.currentThread().getName()
+ "在第" + j
+ "次循环了" + i);
}
subFlag
= false;
this.notify();
}

public synchronized void main(int j) {
while(subFlag) {
try {
this.wait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int i =1; i <=100; i++) {
System.out.println(Thread.currentThread().getName()
+ "在第" + j
+ "次循环了" + i);
}
subFlag
= true;
this.notify();
}
}

经验:要用到共同数据(包括同步锁)或共同算法的若干方法应该归在同一个类身上,这种设计体现了高类聚和程序的健壮性。

互斥、同步、通信问题的逻辑不是写在线程代码上,而是在线程访问那个资源类上。

 

posted on 2011-08-29 17:31 日出星辰 阅读(68) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: