实现一道经典的面试题
首先线程A打印10次,然后给线程B打印5次,然后再给线程A打印10次,然后再给B打印5次,如此循环10次
分析:其实这道题目也就是考察线程的同步以及wait()、notify()的使用。具体实现如下:
public class ThreadWait {
/**
* @param args
*/
public static void main(String[] args) {
final Temp temp = new Temp();
new Thread(){
public void run(){
for (int i = 1; i <= 5; i++) {
try {
temp.methodA(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
new Thread(){
public void run(){
for (int i = 1; i <= 5; i++) {
try {
temp.methodB(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}.start();
}
}
class Temp{
private boolean flag = true ;//互斥变量
public synchronized void methodA(int i) throws InterruptedException{
if(!flag){
this.wait();
}
for (int j = 1; j <= 10; j++) {
System.out.println("methodA "+j+"------"+i);
}
flag = false ;
this.notify();
}
public synchronized void methodB(int i) throws InterruptedException{
if(flag){
this.wait();
}
for (int j = 1; j <= 5; j++) {
System.out.println("methodB "+j+"------"+i);
}
flag = true ;
this.notify();
}
}