// 面试题,子线程10次与主线程100次来回循环执行50次
public class interview {
public static void main(String[] args) {
final Business b = new Business();
new Thread(new Runnable(){
@Override
public void run() {
for (int i = 1; i <= 50; i++) {
b.sub(i);
}
}
}).start();
for (int i = 1; i <= 50; i++) {
b.main(i);
}
}
}
class Business{
private boolean flag;
public synchronized void sub(int i){
while (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 10; j++) {
System.out.println("sub Thread is sequence of "+j+"..lamp of "+i);
}
System.out.println("/..................");
flag = true;
notify();
}
public synchronized void main(int i){
while (!flag) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for (int j = 1; j <= 100; j++) {
System.out.println("main Thread is sequence of "+j+"..lamp of "+i);
}
flag = false;
System.out.println("........................");
notify();
}
}
转载于:https://blog.51cto.com/jiangzuun2014/1538205