(wait notifyAll)多生产多消费
先生产后消费
public class Test {
public static void main(String[] args) throws InterruptedException {
MyStack myStack=new MyStack();
P1 p1=new P1(myStack);
P1 p2=new P1(myStack);
P1 p3=new P1(myStack);
P1 p4=new P1(myStack);
C1 c1=new C1(myStack);
C1 c2=new C1(myStack);
C1 c3=new C1(myStack);
C1 c4=new C1(myStack);
C1 c5=new C1(myStack);
P_Thread1 p_thread1=new P_Thread1(p1);
P_Thread1 p_thread2=new P_Thread1(p1);
P_Thread1 p_thread3=new P_Thread1(p1);
P_Thread1 p_thread4=new P_Thread1(p1);
p_thread1.start();
p_thread2.start();
p_thread3.start();
p_thread4.start();
C_Thread1 c_thread1=new C_Thread1(c1);
C_Thread1 c_thread2=new C_Thread1(c2);
C_Thread1 c_thread3=new C_Thread1(c3);
C_Thread1 c_thread4=new C_Thread1(c4);
c_thread1.start();
c_thread2.start();
c_thread3.start();
c_thread4.start();
}
}
/**
* 生产者
*/
class P1{
private MyStack myStack;
public P1(MyStack myStack) {
this.myStack = myStack;
}
public void push(){
myStack.push();
}
}
/**
* 生产者线程
*/
class P_Thread1 extends Thread{
private P1 p1;
public P_Thread1(P1 p1) {
super();
this.p1 = p1;
}
@Override
public void run() {
while(true){
p1.push();
}
}
}
class C_Thread1 extends Thread{
private C1 c1;
public C_Thread1(C1 c1) {
super();
this.c1 = c1;
}
@Override
public void run() {
while (true){
c1.pop();
}
}
}
/**
* 消费者
*/
class C1{
private MyStack myStack;
public C1(MyStack myStack) {
this.myStack = myStack;
}
public void pop(){
myStack.pop();
}
}
class MyStack {
private List list = new ArrayList();
synchronized public void push() {
try {
while (list.size()==10) {
this.wait();
}
list.add("anyString=" + Math.random());
this.notifyAll();
System.out.println("push=" + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized public String pop() {
String returnValue = "";
try {
while (list.size() == 0) {
System.out.println("pop操作中的:" + Thread.currentThread().getName() + " 线程呈wait状态");
this.wait();
}
returnValue = list.get(0).toString();
list.remove(0);
this.notifyAll();
System.out.println("pop=" + list.size());
} catch (InterruptedException e) {
e.printStackTrace();
}
return returnValue;
}
}