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;
}
}
@Override
public 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 block
e.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 {
@Override
public 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 block
e.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();
}
}
}