(wait notifyAll)多生产多消费

(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;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值