好的,
由于此处的观察者模式超重,我自己尝试了一下。
不知何故咖啡或牛奶都没放在杯子里。
package test;
import java.util.*;
public class Task extends Thread {
private static final Task EMPTY_TASK = null;
private Task postTask = EMPTY_TASK;
private final List<Task> preconditions;
public Task() {
super();
preconditions = Collections.emptyList();
}
public Task(final String name, final Task... preliminaries) {
super(name);
this.preconditions = new ArrayList<Task>(Arrays.asList(preliminaries));
for (Task preliminary : preliminaries) {
preliminary.setPostTask(this);
}
}
private void setPostTask(final Task postTask) {
this.postTask = postTask;
}
@Override
public void run() {
System.out.println("Working " + this);
if (postTask != null) {
postTask.informSolved(this);
}
}
@Override
public synchronized void start() {
if (preconditions.size() == 0) {
super.start();
} else {
System.out.println("The " + getName() + " cant start: " + preconditions
+ " not yet solved.");
}
}
private synchronized void informSolved(final Task task) {
preconditions.remove(task);
start();
}
@Override
public String toString() {
return getName();
}
public static void main(final String[] args) {
Task cup = new Task("Cup");
Task milk = new Task("Milk", cup);
Task coffee = new Task("Coffee", cup);
Task mix = new Task("Mix", milk, coffee);
mix.start();
milk.start();
cup.start();
coffee.start();
}
}
这在控制台上显示:
The Mix cant start: [Milk, Coffee] not yet solved.
The Milk cant start: [Cup] not yet solved.
The Coffee cant start: [Cup] not yet solved.
Working Cup
Working Coffee
The Mix cant start: [Milk] not yet solved.
我的问题:如何混合咖啡?
最佳答案
这就是为什么您不能喝早咖啡的原因:
private void setPostTask(final Task postTask) {
this.postTask = postTask;
}
一个任务只能执行一个后期任务,在您的情况下,杯子需要包含2个-咖啡和牛奶。使postTask成为postTasks
关于java - 不能在我的杯子里混合牛奶和咖啡,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22170749/