使用ReentrantLock以及Condition实现的生产者消费者,也是java 1.5之后推荐写法,不再使用object类的notify()以及wait()方法。直接上代码:
public class Stroge { private final int MAX_SIZE = 100; private LinkedList
测试类:
public class Testprosum { public static void main(String[] args) { Stroge sto = new Stroge(); Producter p1 = new Producter(sto); Producter p2 = new Producter(sto); Producter p3 = new Producter(sto); Producter p4 = new Producter(sto); Producter p5 = new Producter(sto); Consumer c1 = new Consumer(sto); Consumer c2 = new Consumer(sto); Consumer c3 = new Consumer(sto); Consumer c4 = new Consumer(sto); Consumer c5 = new Consumer(sto); p1.setNum(10); p2.setNum(20); p3.setNum(30); p4.setNum(40); p5.setNum(50); c1.setNum(10); c2.setNum(20); c3.setNum(30); c4.setNum(40); c5.setNum(50); p1.start(); p2.start(); p3.start(); p4.start(); p5.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } c1.start(); c2.start(); c3.start(); c4.start(); c5.start(); }}
ReentrantLock需要注意try{}finally{lock.unlock();}
OVER