Is using a join to wait until a Thread has finished the same as using the an observer to notify the calling thread class when the thread has finised ?
Using join -
public class Reader {
Thread t = new Thread(new ReadContent());
t.start();
t.join();
System.out.println("Thread has finished");
public class ReadContent() implements Runnable{
}
public void run() {
readContentURL();
}
}
/*****************************************************************************/
Using observer -
public interface ReadContentListener{
public void contentRead();
}
public class Reader implements ReadContentListener {
Thread t = new Thread(new ReadContent(this));
t.start();
pubic void contentRead(){
System.out.println("Thread has finished");
}
public class ReadContent implements Runnable{
public ReadContent(ReadContentListener readContentListener) {
this.readContentListener = readContentListener;
}
public void run() {
readContentURL();
this.readContentListener.contentRead();
}
}
/*************************************************************/
public GenericScreenAnimation(String nextScreen, Thread genericWorkerThread)
{
this.genericWorkerThread = genericWorkerThread;
this.genericWorkerThread.start();
initialise();
try {
this.genericWorkerThread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
ScreenController.displayNextScreen(nextScreen);
}
The observer pattern is about notifying other objects, not other threads. Your ReadContentListener will be notified in the reading thread if the reading has finished. The original thread during this will continue it's own work (or finish, if there is none).
Using Thread.join makes the original thread simply block until the reading thread is finished.
You would use this normally never directly after .start()
, but only if you have other things to do on the original thread, which should be done in parallel to the reading. Calling this directly after .start()
is (for the effects) equivalent to doing the reading on the original thread.
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