当可观察对象作为新线程运行时,为什么不通知观察者?

时间:2014-04-12 16:45:17

标签: java multithreading design-patterns observer-pattern

我有实现Runnable接口的计算类(为了便于阅读,我简化了它):

public class ColorReduction extends Observable implements Runnable {

    public ColorReduction(Layer inputLayer, Layer outputLayer) {
        this.init();
    }

    private void init() {
        addObserver(new ActionObserver());
    }

    public void run(){

        notifyObservers(EAction.COLOR_REDUCTION_START);
        setChanged();

        // some computation stuff.....

        notifyObservers(EAction.COLOR_REDUCTION_FINISH);
        setChanged();

    }

}

在控制器中我将此类作为新线程运行:

ColorReduction cr = new ColorReduction(model.getInputLayer(), model.getOutputLayer());

            Thread t = new Thread(cr);
            t.start();

问题:观察员(ActionObserver)仅在颜色缩减阶段(COLOR_REDUCTION_FINISH)结束时通知,而不是在此阶段的开始时通知{{1 }})。

我的代码出了什么问题?

1 个答案:

答案 0 :(得分:2)

您需要先调用setChanged():

this.setChanged();
this.notifyObservers(EAction.YOUR_ENUM_VALUE);