假设我有一个对象 Foo,它希望使用侦听器接口从线程的几个正在运行的实例中获取通知。例如
界面:
public interface ThreadListener {
public void onNewData(String blabla);
}
Foo类:
public class Foo implements ThreadListener {
public Foo() {
FooThread th1 = new FooThread();
FooThread th2 = new FooThread();
...
th1.addListener(this);
th2.addListener(this);
...
th1.start();
th2.start();
...
}
@Override
public void onNewData(String blabla) {
...
}
}
主题:
public FooThread extends Thread {
private ThreadListener listener = null;
public void addListener(ThreadListener listener) {
this.listener = listener;
}
private void informListener() {
if (listener != null) {
listener.onNewData("Hello from " + this.getName());
}
}
@Override
public void run() {
super.run();
while(true) {
informListener();
}
}
}
在最坏的情况下,onNewData(..) 会被多个线程同时调用。Foo会发生什么?会不会崩溃?