重要角色:
1.流水线工人:流水线工人主要对传送带上的产品进行加工。
2.流水线传送带:用于传送来自上游的产品
3.产品组装说明书:用于说明该产品如何组装
1.产品组装说明书
public abstract class InstructionBook{
public final void create(){
this.firstProcess();
this.secondProcess();
}
protect abstract void firstProcess();
protect abstract void secondProcess();
}
2.产品
public class production extends InstructionBook{
private final int prodID;
public Production(int prodID){
this.prodID = prodID
}
protected void firstProcess(){
System.out.println("execute the "+prodID+"first process");
}
protected void secondProcess(){
System.out.println("execute the "+prodID+"second process");
}
}
3.流水线传送带
public class ProductionChannel{
//保存产品
private Production[] productions;
//用来记录当前存放的位置 用数组实现队列
private int head;
//用来记录当前取的位置
private int tail;
//用来计算产品总数
private int tatol;
//流水线上最多存在多少个线程
private final static int MAX_PRO = 100;
//工人的数量
private Worker[] workers;
public ProductionChannel(int workSize){
this.workers = new Worker[workSize];
this.productions = new Production[MAX_PRO];
//实例化工人
for(int i=0;i<workSize;i++){
works[i] = new Work("Worker -" +i,productions);
works[i].start();
}
}
//添加产品
public void offerProduction(Production production){
synchronized(this){
while(total >= productions.length){
try{
this.wait();
}catch(Exception e){
}
}
productions[head++] = production;
head = head % MAX_PRO;
total ++;
this.nofityAll();
}
}
//获取产品
public Production takeProduction(){
synchronized(this){
while(total > 0){
this.wait();
}
Production production = productions[tail++];
tail = tail % MAX_PRO;
total --;
this.notifyAll();
return production;
}
}
}
Worker类
public class Worker extends Thread{
private final ProductionChannel productionChannel;
private final static Random random = new Randmon(System.currentTimeMillls());
public Worker(String workerName,ProductionChannel productionChannel){
super(workName);
this.procutionChannel = productionChannel;
}
public void run(){
while(true){
try{
Production production = procutionChannel.takeProduction();
production.create();
TimeUtil.SECONED.sleep(random.nextInt(10));
}catch(Exception e){
}
}
}
}
Worker Thread模式与生产者消费者模式对比