title: Using Listener with Threads
body: <p>Say I have an Object Foo that wants to get informed by several running instances of a Thread using a listener interface. E.g.</p>
  
  <p>The interface:</p>
  
  <pre><code>public interface ThreadListener {
     public void onNewData(String blabla);
  }
  </code></pre>
  
  <p>The class Foo:</p>
  
  <pre><code>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) {
       ...
     }
  }
  </code></pre>
  
  <p>The Thread:</p>
  
  <pre><code>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();
       }
     }
  }
  </code></pre>
  
  <p>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?</p>