通知对象有关线程内的事件

时间:2017-08-09 13:49:51

标签: java multithreading observer-pattern java-threads

我有一个问题是线程和对象在一个线程中初始化,等待来自另一个线程中的对象的通知。假设我有一个可观察的列表,如下例所示:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by Marc van Duyn on 9-8-2017.
 */
public class ObservableList {

    private volatile static ObservableList INSTANCE;
    private List<Integer> mItems = new ArrayList<>();
    private final Set<Observer> mObservers = Collections.newSetFromMap(
            new ConcurrentHashMap<Observer, Boolean>(0));

    private ObservableList() {};

    public static ObservableList getInstance() {

        if(INSTANCE == null) {

            synchronized (ObservableList.class) {

                if(INSTANCE == null) {
                    INSTANCE = new ObservableList();
                }
            }
        }
        return INSTANCE;
    }

    public void registerObserver(Observer observer) {

        if (observer != null) {
            mObservers.add(observer);
        }
    }

    /**
     * This method removes an Observer - it will no longer be notified when Observable changes
     */
    public void unregisterObserver(Observer observer) {

        if (observer != null) {
            mObservers.remove(observer); // this is safe due to thread-safe Set
        }
    }

    public void addListItem(final Integer itemIn) {

        if(itemIn != null) {
            this.mItems.add(itemIn);

            for(Observer lObserver: this.mObservers) {
                lObserver.update("Item added " + itemIn);
            }
        }
    }
}

当我在线程中实例化一个观察者时,ObservableList无法丰富观察者。我知道这是由于runnable接口的run方法。但是有没有办法更新在线程中实例化的对象?

这是我的主题:

import Observers_Observable.ObservableList;
import Observers_Observable.Observer;

/**
 * Created by Marc van Duyn on 9-8-2017.
 */
public class ObserverThread implements Runnable {
    private Thread mThread;

    public ObserverThread() {
        this.mThread = new Thread(this);
        Observer lObserver = new Observer(1);
        ObservableList.getInstance().registerObserver(lObserver);
        lObserver = new Observer(2);
        ObservableList.getInstance().registerObserver(lObserver);
        lObserver = new Observer(3);
        ObservableList.getInstance().registerObserver(lObserver);
        this.mThread.start();
    }

    @Override
    public void run() {

        //Wait for notify...........
        while(true) {
            /**
             * I don't know if my observers ever will be notified, because
             * this code is inside a while loop. This is the problem with threads
             * and observer objects inside a thread.
             */
        }
    }

    //Join method of the thread
    public void join() throws InterruptedException {
        this.mThread.join();
    }
}

0 个答案:

没有答案