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

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 skinQueue;private static AtomicInteger id=new AtomicInteger();private boolean isShutdown;public DoSkin(BlockingQueue 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 skinQueue;private final MakeThread makeThread;private boolean isShutdown;public MakeDumpling(BlockingQueue 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 queue = new ArrayBlockingQueue(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();}}}



本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部