// object类的notify(),notifyall(),wait,wait(long),wait(long,int)
// object.wait(); 使拥有当前对象object的线程进入睡眠状态,放弃锁release lock;
// notify() 通知在对象上因调用wait()而处于睡眠状态的某一线程启动;
// notifyAll() 通知在对象上因调用wait()而处于睡眠状态的所有线程启动,这些进程根据优先级顺序执行;
class Q {
int n;
boolean valueSet = false;
public synchronized int get() {
if (!valueSet)
try {
this.wait(); // 使当前使用该对象的线程睡眠
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Get n = " + n);
valueSet = false;
notify(); // 通知一个线程可以调用该线程了
return n;
}
public synchronized void put(int n) {
// if valueSet == true,already have value so wait fetch,else put
if (valueSet)
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
this.n = n;
System.out.println("Put n = " + n);
valueSet = true;
notify();
}
}
class Producer implements Runnable {
Q q = null;
Producer(Q q) {
this.q = q;
(new Thread(this, "Producer")).start();
}
@Override
public void run() {
int i = 0;
while (i < 10) {
q.put(i++);
}
}
}
class Consumer implements Runnable {
Q q = null;
public Consumer(Q q) {
this.q = q;
(new Thread(this, "Consumer")).start();
}
@Override
public void run() {
while (q.get() < 9) {
}
}
}
public class DemoThread {
public static void main(String[] args) {
Q q = new Q();
new Consumer(q);
new Producer(q);
}
}