生产者消费者模式(java)

来源:互联网 发布:巴以冲突的根源 知乎 编辑:程序博客网 时间:2024/05/09 19:51

所谓的生产者消费者模式,也就是线程之间的通信的经典实现。

多个线程处理同一个资源,并且处理的方式也不同,各个线程之间,彼此还有有交流。

比如,我放入篮子里水果后,你才可以往外拿。

1、需要线程停下来的时候,用wait

2、需要唤醒线程池中的线程时候,用notify


class Resource11{  private String name;  private int num;  private boolean flag;  public synchronized void set(String name)  {    if(flag)  try{  wait();  }     catch(InterruptedException e){}    this.name = name;  num++;  System.out.println("shenchanzhe"+num);  flag = true;  notify();  }  public synchronized void out()  {  if(flag==false)  {  try{  wait();  }     catch(InterruptedException e){}  }    num--;  System.out.println("消费者");  flag = false;  notify();  }}//生产者线程class Product implements Runnable{private Resource11 r;    public Product(Resource11 r)    {    this.r = r;    }public void run(){while(true){r.set("apple");}}}class Con1 implements Runnable{private Resource11 r;    public Con1(Resource11 r)    {    this.r = r;    }public void run(){while(true){r.out();}}}//消费者线程public class ProCon {public static void main(String[] args){Resource11 r = new Resource11();Product p = new Product(r);Con1 c = new Con1(r);Thread t1 = new Thread(p);Thread t2 = new Thread(c);t1.start();t2.start();}}


0 0
原创粉丝点击