【问题标题】:Why observer is not notified when observable object runs as new thread?为什么当可观察对象作为新线程运行时没有通知观察者?
【发布时间】:2014-04-12 16:45:17
【问题描述】:

我有实现 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) 结束时收到通知,而不是在此阶段开始时 (COLOR_REDUCTION_START) 收到通知。 p>

我的代码有什么问题?

【问题讨论】:

    标签: java multithreading design-patterns observer-pattern


    【解决方案1】:

    你需要先调用 setChanged():

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

    【讨论】:

      猜你喜欢
      • 2011-06-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-09
      相关资源
      最近更新 更多