许久没来这里了,今天找了个面试题,随便搞搞
/**
* 子线程循环10次,接着主线程循环100,接着子线程循环10次,接着主线程循环100,如此循环50次
* @author lenovo
*
*/
public class Test2 {
public static void main(String[] args) {
final MyThread myThread = new MyThread();
new Thread(
new Runnable(){
@Override
public void run() {
for(int i=0;i<50;i++){
System.out.println("sub is "+i +" count");
myThread.sub();
}
}
}).start();
for (int i = 0; i < 50; i++) {
System.out.println("main is "+i +" count");
myThread.main();
}
}
}
/**
* 线程类
* @author lenovo
*
*/
class MyThread{
/**
* 标志子线程调用方法是否被调用
*/
private boolean bSubIsRuned = true;
/**
* 子线程调用方法
*/
public synchronized void sub(){
while(!bSubIsRuned){//如果子线程方法没被调用,即调用了主线程方法
//等待别的线程使用
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
for(int i = 0 ;i<10;i++){
System.out.println("sub:" + i);
}
//子方法被调用完成后
bSubIsRuned = false;
//唤醒别的在等待的线程
this.notify();
}
/**
* 主线程调用方法
*/
public synchronized void main(){
while(bSubIsRuned){//如果主方法没被调用,即子方法被调用
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
for(int i = 0 ;i<100;i++){
System.out.println("main:" + i);
}
bSubIsRuned = true;
this.notify();
}
}