/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package NewCoder;
/**
*
* @author MI
*/
class SharedObject {
boolean flag = false;
synchronized void waitForFlag() {
while (!flag) {
try {
wait();//默认已有方法
} catch (InterruptedException e) {
System.out.println("Thread interrupted while waiting for flag");
//throw e;
e.printStackTrace();
}
}
//perform action
System.out.println("Flag is now true,perform action...current thread is :" + Thread.currentThread().getName());
notify();
}
synchronized void setFlag() {
flag = true;
notify();
}
}
class Thread1 extends Thread {
SharedObject sharedObject;
Thread1(SharedObject sharedObject) {
this.sharedObject = sharedObject;
}
public void run() {
System.out.println("Thread1 waiting for flag to be set");
sharedObject.waitForFlag();
}
}
class Thread2 extends Thread {
SharedObject sharedObject;
Thread2(SharedObject sharedObject) {
this.sharedObject = sharedObject;
}
public void run() {
System.out.println("Thread2 setting flag");
sharedObject.setFlag();
}
}
public class Main {
public static void main(String[] args) {
SharedObject sharedObject = new SharedObject();
for(int i = 0; i < 5; i++) {
new Thread1(sharedObject).start();
}
Thread2 thread2 = new Thread2(sharedObject);
thread2.start();
}
}
修改1:
synchronized void waitForFlag() {
while (!flag) {
try {
wait();//默认已有方法
} catch (InterruptedException e) {
System.out.println("Thread interrupted while waiting for flag");
//throw e;
e.printStackTrace();
}
}
//perform action
System.out.println("Flag is now true,perform action...current thread is :" + Thread.currentThread().getName());
try {
wait();notify();//不执行notify()
} catch (InterruptedException e) {}
}
修改2:
修改3: