上次模拟的是用缓存,这次模拟信号灯。假设流水线上不断的输送零件,工人装配一个零件然后发出信号表示装配完毕,然后收到信号后引擎动一下,让流水线取出下一个零件,引擎再发出信号,表示下一个零件拿来了,然后工人继续装配,循环往复。
public class Test {
public static void main(String[] args) {
Pipeline Pipeline = new Pipeline();
new Worker(Pipeline).start();
new Engine(Pipeline).start();
}
}
class Pipeline{
boolean flag = true;
public synchronized void make() {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("装配零件");
this.notify();
this.flag=!this.flag;
}
public synchronized void move() {
if(flag) {
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("取下一个零件");
this.notify();
this.flag=!this.flag;
}
}
class Worker extends Thread{
Pipeline Pipeline;
public Worker(Pipeline Pipeline) {
this.Pipeline = Pipeline;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 20; i++) {
Pipeline.make();
}
}
}
class Engine extends Thread{
Pipeline Pipeline;
public Engine(Pipeline Pipeline) {
this.Pipeline = Pipeline;
}
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 20; i++) {
Pipeline.move();
}
}
}