使用BlockingQueue实现包饺子( 生产者做面皮,消费者拿面皮包饺子)简单使用

来源:互联网 发布:数据条带化 编辑:程序博客网 时间:2024/04/27 16:41
package com.zghw.concurrent.BlockingQueue;import java.util.concurrent.atomic.AtomicInteger;/** * 饺子皮对象 * @author zghw * */public class Skin {//序号private int num;//面皮厚度private double thick;public Skin(AtomicInteger id, double thick) {this.num = id.get();this.thick=thick;}public double getThick() {return thick;}public void setThick(double thick) {this.thick = thick;}public int getNum() {return num;}public void setNum(int num) {this.num = num;}public String toString(){return "面皮"+num+" 厚度为:"+thick+"mm";}}

生产者:

package com.zghw.concurrent.BlockingQueue;import java.util.Random;import java.util.concurrent.BlockingQueue;import java.util.concurrent.atomic.AtomicInteger;/** * 做面皮用来包饺子 * @author zghw * */public class DoSkin implements Runnable{private final BlockingQueue<Skin> skinQueue;private static AtomicInteger id=new AtomicInteger();private boolean isShutdown;public DoSkin(BlockingQueue<Skin> skinQueue ){this.skinQueue=skinQueue;isShutdown = false;}public void stop() {synchronized (this) {isShutdown = true;}}@Overridepublic void run() {while(true){synchronized (this) {if (isShutdown) {break;}}id.getAndIncrement();double thick =((int)(Math.random()*1000))+0.99;Skin sk=new Skin(id,thick);System.out.println("做 "+sk);/*try {Thread.sleep((int)(Math.random()*1000)+1);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}*/skinQueue.offer(sk);}}}


消费者:

package com.zghw.concurrent.BlockingQueue;import java.util.concurrent.BlockingQueue;/** * 使用面皮包饺子 *  * @author zghw * */public class MakeDumpling {private final BlockingQueue<Skin> skinQueue;private final MakeThread makeThread;private boolean isShutdown;public MakeDumpling(BlockingQueue<Skin> skinQueue) {this.skinQueue = skinQueue;makeThread = new MakeThread();isShutdown = false;}public void start() {makeThread.start();}public void stop() {synchronized (this) {isShutdown = true;}makeThread.interrupt();}private class MakeThread extends Thread {@Overridepublic void run() {while (true) {synchronized (this) {if (isShutdown) {break;}}Skin skin = skinQueue.poll();if (skin != null) {/*try {// Thread.sleep((int) (Math.random() * 1000) + 1);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}*/System.out.println("使用 " + skin + " ,包饺子");}}}}}

package com.zghw.concurrent.BlockingQueue;import java.util.concurrent.*;public class MakeDumplings {public static void main(String[] args) {BlockingQueue<Skin> queue = new ArrayBlockingQueue<Skin>(100);ExecutorService exc = Executors.newFixedThreadPool(20);MakeDumpling md=new MakeDumpling(queue);DoSkin ds=new DoSkin(queue);md.start();exc.execute(ds);try {Thread.sleep(10000);ds.stop();md.stop();} catch (InterruptedException e) {e.printStackTrace();}}}


0 0
原创粉丝点击