生产者和消费者

xiaoxiao2021-02-28  42

通过wait notifyAll编写生产者和消费者代码

public class ProduceConsumer { public static void main(String[] args) { Resource resource = new Resource(); Produce pro1 = new Produce(resource); Produce pro2 = new Produce(resource); Consumer con = new Consumer(resource); pro1.start(); pro2.start(); con.start(); } } class Resource{ private int num = 0; private int size = 10; public synchronized void remove() throws InterruptedException{ if(num>0){ num--; System.out.println("消费者为"+Thread.currentThread().getName()+"消费一件,当前线程为"+num+"件"); notifyAll(); }else{ wait(); System.out.println("无数据,等待生产者生产"); } } public synchronized void add() throws InterruptedException{ if(num<size){ num++; System.out.println("生产者为"+Thread.currentThread().getName()+"生产一件,当前线程为"+num+"件"); notifyAll(); }else{ wait(); System.out.println("数据已满,等待消费"); } } } class Produce extends Thread{ private Resource resource; public Produce(Resource resource){ this.resource=resource; } public void run(){ while (true) { try { Thread.sleep(100); resource.add(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } class Consumer extends Thread { private Resource resource; public Consumer(Resource resource){ this.resource=resource; } public void run(){ while (true) { try { Thread.sleep(100); resource.remove(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
转载请注明原文地址: https://www.6miu.com/read-2800067.html

最新回复(0)