三线程制作面包流水线
三个师傅,A师傅做面包,B师傅打包,C师傅出餐,要按A->B->C->A->B->C...的顺序执行,生产十个面包
public class BreadMaker {
public static void main(String[] args) throws InterruptedException {
BreadMaker breadMaker = new BreadMaker();
breadMaker.myRun();
}
private static int count = 10;
private void myRun() throws InterruptedException {
BlockingQueue<Bread> bqa = new LinkedBlockingQueue<>();
BlockingQueue<Bread> bqb = new LinkedBlockingQueue<>();
BlockingQueue<Bread> bqc = new LinkedBlockingQueue<>();
for (int i = 0; i < count; i++) {
bqa.add(new Bread(i));
}
BreadPipeline breadMaker = new BreadPipeline(bqa, bqb, (bread)->{
bread.make();
Thread.sleep(500);
System.out.println(bread + "make完成");
});
BreadPipeline breadPacker = new BreadPipeline(bqb, bqc, (bread)->{
bread.pack();
Thread.sleep(500);
System.out.println(bread + "pack完成");
});
BreadPipeline breadOuter = new BreadPipeline(bqc, null, (bread)->{
bread.out();
Thread.sleep(500);
System.out.println(bread + "out完成");
});
breadMaker.start();
breadPacker.start();
breadOuter.start();
System.out.println("wan cheng");
Thread.sleep(20000);
System.out.println(bqc);
}
class Bread{
long id;
volatile byte state; // 0 代表初始化, 1代表制作完成,2代表打包完成,3代表出餐,-1代表废弃
public Bread(int num){
id = num;
state = 0;
}
private boolean make(){
if (this.state == 0){
state = 1;
return true;
}
return false;
}
private boolean pack(){
if (this.state == 1){
state = 2;
return true;
}
return false;
}
private boolean out(){
if (this.state == 2){
state = 3;
return true;
}
return false;
}
@Override
public String toString() {
return "{id:"+id+",state:"+state+"}";
}
}
class BreadPipeline extends Thread{
private BlockingQueue<Bread> currList;
private BlockingQueue<Bread> nextList;
PipelineTask task;
public BreadPipeline(BlockingQueue<Bread> currList,BlockingQueue<Bread> nextList,PipelineTask task){
this.nextList = nextList;
this.currList = currList;
this.task = task;
}
@Override
public void run() {
try {
while (true) {
Bread bread = currList.take();
task.doTask(bread);
if (nextList != null) {
nextList.put(bread);
}
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
interface PipelineTask{
public void doTask(Bread bread) throws InterruptedException;
}
}
多线程编程面试题 文章被收录于专栏
收录面试中多线程编程的手撕题目和答案
