歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java線程wait()與notify()

Java線程wait()與notify()

日期:2017/3/1 10:45:28   编辑:Linux編程

實現一道經典的面試題

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

}

Copyright © Linux教程網 All Rights Reserved