wait()与notify()是Java线程同步机制最重要的两个方法。wait方法可以使在当前线程的对象等待,直到别的线程调用此对象的notify或notifyAll方法。
生产者线程类如下:
class Producer implements Runnable {
Buffer q;
Producer(Buffer q) {
this.q = q;
new Thread(this, "Producer").start();
}
publicvoid run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
Buffer q;
Producer(Buffer q) {
this.q = q;
new Thread(this, "Producer").start();
}
publicvoid run() {
int i = 0;
while(true) {
q.put(i++);
}
}
}
消费者线程类如下:
class Consumer implements Runnable {
Buffer q;
Consumer(Buffer q) {
this.q = q;
new Thread(this, "Consumer").start();
}
publicvoid run() {
while(true) {
q.get();
}
}
}
Buffer q;
Consumer(Buffer q) {
this.q = q;
new Thread(this, "Consumer").start();
}
publicvoid run() {
while(true) {
q.get();
}
}
}
Main函数:
publicclass Sample {
publicstaticvoid main(String args[]) {
Buffer q = new Buffer();
new Consumer(q);
new Producer(q);
System.out.println("Press Ctrl-C to stop.");
}
}
publicstaticvoid main(String args[]) {
Buffer q = new Buffer();
new Consumer(q);
new Producer(q);
System.out.println("Press Ctrl-C to stop.");
}
}