Say I have an Object Foo that wants to get informed by several running instances of a Thread using a listener interface. E.g.
The interface:
public interface ThreadListener {
public void onNewData(String blabla);
}
The class 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) {
...
}
}
The Thread:
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();
}
}
}
In the worst case onNewData(..) is invoked by several threads at the same time. What will happen with Foo? Is it going to crash or not?
Foo class has no state (fields), so unless it uses external shared resources (e.g. files...) it is thread safeonNewData does not access shared data it will work as expected, if it does, the outcome will depend on how the method is implemented.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With