import java.util.Vector;
public class Producer implements Runnable{
private Vector<Integer> capacity = null;
public Producer(Vector<Integer> capacity) {
this.capacity = capacity;
}
@Override
public void run() {
try {
synchronized(capacity) {
while(capacity.size() == 100) {
//wait()之前必须获得对象锁
capacity.wait();
}
Integer x = (int) (Math.random() * 10000);
System.out.println("product:" + x);
capacity.add(x);
//notifyAll()之前必须获得对象锁
capacity.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.Vector;
public class Consumer implements Runnable{
private Vector<Integer> capacity = null;
public Consumer(Vector<Integer> capacity) {
this.capacity = capacity;
}
@Override
public void run() {
try {
synchronized (capacity) {
while(capacity.isEmpty()) {
//wait()之前必须获得对象锁
capacity.wait();
}
capacity.remove(0);
System.out.println("consumer:size=" + capacity.size());
//notifyAll()之前必须获得对象锁
capacity.notifyAll();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
import java.util.Vector;
public class TestWaitNofity {
public static void main(String[] args) {
Vector<Integer> capacity = new Vector<Integer>();
Producer producer = new Producer(capacity);
Consumer consumer = new Consumer(capacity);
for(int i = 0; i < 100; i++) {
Thread t = new Thread(producer);
t.start();
}
for(int i = 0; i < 100; i++) {
Thread t = new Thread(consumer);
t.start();
}
}
}