生产者消费者JAVA实现
好久没动过java了,今天给朋友写这个生产者消费者的小程序,结果遇到了很多麻烦,尤其是synchronized那块,整了好多遍都没有成功,最后看了一下,发现自己锁定对象锁定错了,一直在锁定类。哎,自己还是差的好多好多啊,真是必须要努力练习啊,不能荒废着!希望各位大牛们可以看看帮忙指点下,这个程序的不足肯定很多很多,
public class Depot { /** * 仓库类 */ public synchronized boolean get(){ if(count>0){ count--; return true; }else{ return false; } } public synchronized boolean add(){ if(count >=0 && count <10){ count++; sum++; return true; }else{ return false; } } public int getCount(){ return count; } public int getSum(){ return sum; } private static int count=0; private static int sum=0; }
public class Preducer extends Thread{ /** * 生产者 */ public Preducer(Depot depot,String name){ super(name);//调用Thread的 构造方法 this.depot=depot; } public void run(){ while(true){ if(depot.add()){ synchronized (depot){ System.out.println(Thread.currentThread().getName()+"生产了1个馒头,库存还有"+depot.getCount()+"个馒头,累计生产了"+depot.getSum()+"个馒头."); try { sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } depot.notifyAll(); } /* * 这里一定要这么写,首先sychronized的可以用来锁定某个对象使其只能在同一时间被一个线程所占有, * 而不能同时被两个或两个以上的进程所占有,sychronized块中不能写this,否则是说生产者或者消费者不能被同时占有了, * 而不是我们想要的让仓库不能被同时占有,所以要写仓库类,而且要注意,这里要写个引用类数据(也就是一个对象),而不要写简单类型的数据; * 然后notify和wait不能同时在一个sychronized块中出现,否则就是变成顺序执行了,先执行第一个在执行第二个....直到最后一个 * 然后从头开始继续执行,就失去多线程的意义了。 */ }else{ synchronized (depot){ System.out.println("库房满了!"); try { depot.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } private Depot depot; }
public class Consumer extends Thread{ /** * 消费者 */ public Consumer(Depot depot,String name){ super(name); this.depot=depot; } public void run(){ while(true){ if(depot.get()){ synchronized(depot){ System.out.println(Thread.currentThread().getName()+"消费了一个馒头,库存还有:"+depot.getCount()+"个馒头"); try { sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } depot.notifyAll(); } }else{ synchronized(depot){ System.out.println("没有了!!!"); try { depot.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } } } private Depot depot; }
public class PreducerConsumerTest { /** * 测试类 */ public static void main(String[] args){ Depot depot=new Depot(); Preducer preducer1=new Preducer(depot,"preducer1"); Preducer preducer2=new Preducer(depot,"preducer2"); Consumer consumer1=new Consumer(depot,"consumer1"); Consumer consumer2=new Consumer(depot,"consumer2"); Consumer consumer3=new Consumer(depot,"consumer3"); preducer1.start(); preducer2.start(); consumer1.start(); consumer2.start(); consumer3.start(); } }

浙公网安备 33010602011771号