分类: Java
2012-09-28 17:52:59
/*
* ibm 笔试题: 子线程循环10次,接着主线程循环20,接这又回到子线程循环10次,
* 接着再回到主线程又循环20此。如此循环20次,请写出程序;
*/
public class TraditionalThreadCommunitcation {
public static void main(String[] args) {
final Business business = new Business();
new Thread(new Runnable() {
@Override
public void run() {
//循环20次
for (int i = 0; i <= 20; i++) {
//创建一个子线程循环10次
business.sub(i);
}
}
}).start();
//循环20次
for (int i = 0; i <= 20; i++) {
//main 就是主线程 循环20次
business.main(i);
}
}
}
//将业务抽象到一个匿名类里面然后,实现2者之间互斥同时,依据条件,实现相互间的通信
class Business {
private boolean bShouldSub = true;
public synchronized void sub(int i) {
if (!bShouldSub) {//或者换成while
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 0; j <= 10; j++) {
System.out.println("sub thread squence of " + j + ",loop of " + i);
}
//更改标志位
bShouldSub = false;
//唤醒 主线程
this.notify();
}
public synchronized void main(int i) {
if (bShouldSub) {//或者换成while
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 0; j <= 20; j++) {
System.out.println("main thread squence of " + j + ",loop " + i);
}
//更改标志位
bShouldSub = true;
//唤醒 子线程
this.notify();
}
}