java - 可以在我的杯子里混合牛奶和咖啡

标签 java multithreading

嗯好的,

由于Observer-Pattern在这里超重,我自己尝试。

不知何故,咖啡或牛奶没有放入杯子中。

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;
}

一个任务只能有一个 post 任务,在你的情况下 cup 需要有 2 - coffee 和 milk。将 postTask 变成 postTasks

关于java - 可以在我的杯子里混合牛奶和咖啡,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22170749/

相关文章:

java - 按下按钮时启动无限循环线程,再次按下按钮时停止

java - 在 Jboss AS 7.1 中指定日志级别

java - 需要转义字符串中的 double 字符或一些特殊字符

c# - .NET (C#) 进程和 Adob​​e Acrobat

java - 如何在 C# 和 Java 进程之间使用互斥体?

java - 在java中绘图?

java - 如何将字符串(使用 g.drawString)置于屏幕中央

c++ - lua_newstate 与 lua_newthread

java - 线程不可预测的行为

c++ - 我可以在核心 i7 上获得的最大 cpu 使用率是多少