当前位置 : 主页 > 编程语言 > c++ >

java多线程经典问题-------生产者、消费者问题

来源:互联网 收集:自由互联 发布时间:2021-07-03
gistfile1.txt public class ProducerAndConsumer {/** * title:main * function: *@author dcl *@param args */static List hotDogs = new ArrayList (); //热狗集合 public static void main(String[] args) { for(int i = 1;i4;i++){ new Thread(new P
gistfile1.txt
public class ProducerAndConsumer {

	/**
	 *

title:main

*

function:

*@author dcl *@param args */ static List hotDogs = new ArrayList (); //热狗集合 public static void main(String[] args) { for(int i = 1;i<4;i++){ new Thread(new Producer(i)).start(); } for(int j = 1;j<5;j++){ new Thread(new Consumer(j)).start(); } try { Thread.sleep(5000); System.exit(2); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } static class Producer implements Runnable{ private int pid = -1; int i = 1; //标识热狗编号 public Producer(int pid) { this.pid = pid; } @Override public void run() { /** * 生产者生产热狗,只要有热狗生产出来就可以唤醒所有的等待线程, * 热狗数量超过了展示台5个,就等待消费 */ while(true){ try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }//模拟生产消耗时间 synchronized(hotDogs){ if(hotDogs.size() < 5){ //添加热狗--生产 hotDogs.add(pid*100+i); System.out.println(pid+"号热狗师傅生产"+pid*100+i+"号热狗"); i++; //有了热狗就可以叫消费者来吃 hotDogs.notifyAll(); }else{ System.out.println("热狗拷满了,快来吃啊!"); try { hotDogs.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }//等待 } } } } } static class Consumer implements Runnable{ private int cid = -1; public Consumer(int cid) { this.cid = cid; } @Override public void run() { /** * 消费者者生产热狗,只要消费了热狗就可一唤醒所有等待进程, * 热狗数量超过了展示台5个,就等待生产 */ while(true){ try { Thread.sleep(200); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }//模拟生产消耗时间 synchronized(hotDogs){ if(hotDogs.size() > 0){ //添加热狗--生产 System.out.println("消费者" + this.cid + "正在消费一个热狗,其编号为:" + hotDogs.remove(0)); //有了热狗就可以叫消费者来吃 hotDogs.notifyAll(); }else{ System.out.println("热狗mei了,快点做啊!"); try { hotDogs.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }//等待 } } } } } }
网友评论