您的位置:首页 > 其它

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

2011-08-29 17:31 393 查看
子线程先循环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();
}
}


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

互斥、同步、通信问题的逻辑不是写在线程代码上,而是在线程访问那个资源类上。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: