`
huobengluantiao8
  • 浏览: 1030947 次
文章分类
社区版块
存档分类
最新评论

Java线程wait()与notify()

 
阅读更多

实现一道经典的面试题

首先线程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();
}

}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics