备注:
wait、notify方法必须在synchronized块中使用
面试题:主线程运行10次,子线程运行10次;主、子线程交替执行50次
/**
* 线程通讯
* 要求:
* 主线程运行10次,子线程运行10次
* 主、子线程交替执行50次
*
*/
public class ThreadTest2 {
public static void main(String[] args) {
final Business business=new Business();
//子线程
new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<=50;i++)
business.child(i);
}
}).start();
//主线程
for(int i=1;i<=50;i++)
business.main(i);
}
}
class Business{
private boolean childFlag=true;
public synchronized void main(int i){
//使用while判断的目的是为了防止线程假唤醒的情况
while(!childFlag){
try {
this.wait();//等
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=10;j++){
System.out.println("main-->i:"+i+";j:"+j);
}
childFlag=false;
this.notify();//唤醒等待的进程
}
public synchronized void child(int i){
while(childFlag){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int j=1;j<=10;j++){
System.out.println("child-->i:"+i+";j:"+j);
}
childFlag=true;
this.notify();
}
}