题目:RobotA(负责向盒子中放药)——>RobotB(负责盖盒子)——>RobotC(贴标签)
分析:在流水线作业中,每一个过程都是有先后顺序的。对于同一个盒子,显然需要先放药,再盖盖子再贴标签。可以容易的想到使用wait和notify方法。于是就写了如下解决方案:
public class Pipeline {
/*
* A操作步骤
*/
class RobotAThread extends Thread{
@Override
public void run() {
System.out.println("正在给盒子放药");
synchronized (String.class) {
String.class.notify();
}
}
}
/*
* B操作步骤
*/
class RobotBThread extends Thread{
@Override
public void run() {
synchronized(String.class) {
try {
String.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("正在给盒子盖盖子");
synchronized (Integer.class) {
Integer.class.notify();
}
}
}
/*
*C操作步骤
*/
class RobotCThread extends Thread{
@Override
public void run() {
synchronized (Integer.class) {
try {
Integer.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("正在给盒子贴标签");
}
}
public static void main(String[] args) {
Pipeline pipeline = new Pipeline();
RobotAThread robotAThread = pipeline.new RobotAThread();
RobotBThread robotBThread = pipeline.new RobotBThread();
RobotCThread robotCThread = pipeline.new RobotCThread();
robotAThread.start();
robotBThread.start();
robotCThread.start();
}
}
在这个方案中,总的思路就是B等待A执行完再执行,C等待B执行完再执行。看似完美的解决方案,却得到了如下的运行结果:
此时,先执行完B之后再执行C,使C一直处于wait状态。所以,需要对方案进行改进。
public class Pipeline {
private boolean flagA=true;
private boolean flagB=true;
/*
* A操作步骤
*/
class RobotAThread extends Thread{
@Override
public void run() {
System.out.println("正在给盒子放药");
flagA=false;
synchronized (String.class) {
String.class.notify();
}
}
}
/*
* B操作步骤
*/
class RobotBThread extends Thread{
@Override
public void run() {
if (flagA) {
synchronized (String.class) {
try {
String.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("正在给盒子盖盖子");
flagB=false;
synchronized (Integer.class) {
Integer.class.notify();
}
}
}
/*
*C操作步骤
*/
class RobotCThread extends Thread{
@Override
public void run() {
if (flagB) {
synchronized (Integer.class) {
try {
Integer.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
System.out.println("正在给盒子贴标签");
}
}
public static void main(String[] args) {
Pipeline pipeline = new Pipeline();
RobotAThread robotAThread = pipeline.new RobotAThread();
RobotBThread robotBThread = pipeline.new RobotBThread();
RobotCThread robotCThread = pipeline.new RobotCThread();
robotAThread.start();
robotBThread.start();
robotCThread.start();
}
}
在B和C执行wait方法前,先分别判断A和B是否已经执行完。就可解决之前发生的问题啦!