天天看点

java5个生产者5个消费者_java多线程之--多的生产者与多个消费者

package com.qianfeng.day22_Thread;

public class Demo04 {

public static void main(String[] args) {

Produce04 p = new Produce04();

Customer04 c = new Customer04();

Thread t1 = new Thread(p, "生产者1");

Thread t2 = new Thread(p, "生产者2");

Thread t3 = new Thread(p, "生产者3");

Thread t4 = new Thread(c, "消费者1");

Thread t5 = new Thread(c, "消费者2");

Thread t6 = new Thread(c, "消费者3");

t1.start();

t2.start();

t3.start();

t4.start();

t5.start();

t6.start();

}

}

class Baozi04 {

public static int sum = 0;

}

class Produce04 implements Runnable {

@Override

public void run() {

while (true) {

synchronized (Baozi04.class) {

while (Baozi04.sum >= 5) {

try {

Baozi04.class.wait(); // 等待,释放锁

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

try {

Thread.currentThread().sleep(1000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

Baozi04.sum++;

System.out.println(Thread.currentThread().getName() + "生产了1个包子,共有包子" + Baozi04.sum);

Baozi04.class.notify();

}

}

}

}

class Customer04 implements Runnable {

@Override

public void run() {

while (true) {

synchronized (Baozi04.class) {

while (Baozi04.sum == 0) {

try {

Baozi04.class.wait(); // 等待,释放锁

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

try {

Thread.currentThread().sleep(1000);

} catch (InterruptedException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

Baozi04.sum--;

System.out.println(Thread.currentThread().getName() + "消费了1个包子,还剩" + Baozi04.sum);

Baozi04.class.notify();

}

}

}

}