package com.susan.thread;
/**
* 四、线程的同步问题
*
*
* 示例:
* 写出设计出一个实施方案:子线程执行10,接着主线程执行100次,再次子线程执行10,接着主线程执行100次,这样循环50次。
*
* @author dahai
*
*/
public class TradotionalThreadCommunication {
public static void main(String[] args) {
// TODO Auto-generated method stub
BusinessDao b = new BusinessDao();
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 50; i++) {
b.sub(i);
}
}
}).start();
for (int i = 0; i < 50; i++) {
b.main(i);
}
}
public static class BusinessDao {
private boolean isSubThread =true;
public synchronized void sub(int i) {
while (!isSubThread) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("sub thread sequence of " + i + ",loop of " + j);
}
isSubThread = false;
this.notify();
}
public synchronized void main(int i) {
while (isSubThread) {
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 " + i + ",loop of " + j);
}
isSubThread = true;
this.notify();
}
}
}