public class TraditionalThreadCommunication {
/**
* @param args
* 这个例子可以理解java的通信机制
* 题目是子线程运行10次,主线程运行100次,然后重复50次
* 遇到这种需求的题目,一般要把结构想清楚,最好把做的同样的事放在一个类
* 机构里面来管理,方便同步和通信
*/
public static void main(String[] args) {
final Business business = new Business();
new Thread(
new Runnable() {
@Override
public void run() {
for(int i=1;i<=50;i++){
//子线程运行10次 总共50次
business.sub(i);
}
}
}
).start();
// 主线程运行100次,然后重复50次
for(int i=1;i<=50;i++){
business.main(i);
}
}
}
// 核心通信类
class Business {
// 用来控制通信与互斥的变量
private boolean bShouldSub = true;
// 首先synchronized同步只是保证了执行十次里面的逻辑可以同步,但是
// 并不能保证线程之间来回的同步,所以,除了加synchronized外,还必须
// 试用线程等待和激活机制来控制
public synchronized void sub(int i){
while(!bShouldSub){
try {
// 线程等待
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 执行10次
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=100;j++){
System.out.println("main thread sequence of " + j + ",loop of " + i);
}
bShouldSub = true;
this.notify();
}
}
2021

被折叠的 条评论
为什么被折叠?



