Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using observer pattern as a notifier same as using Thread.join?

Tags:

java

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);
}
like image 817
blue-sky Avatar asked Jun 09 '11 13:06

blue-sky


1 Answers

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.

like image 189
Paŭlo Ebermann Avatar answered Oct 18 '22 03:10

Paŭlo Ebermann