Singleton Thread and Runnable

If class implements runnable and is singleton
if two thread can share the same object of runnable implementor without any Error
//SingletonRunnable  implements Runnable  and is singleton

              SingletonRunnable runnable1 = SingletonRunnable.getInstance();
              SingletonRunnable runnable2 = SingletonRunnable.getInstance();
              /**
               * runnable1 and runnable2 are same instance which are shared for
               * two thread. so there is no IllegalThreadStateException.
               * */
              Thread t1 = new Thread(runnable1);
              Thread t2 = new Thread(runnable2);
              t1.start();
              t2.start();

if a Class extends thread and is singleton
if two thread can share the same object of thread as a super class they will not run
because it will return the same instance of "thread" and thread cannot be started twice
              // Here we are using thread class
//SingletonThread extends Thread and is Singleton
              Thread t3 = SingletonThread.getInstance();
              Thread t4 = SingletonThread.getInstance();
              t3.start();
              /**
               * t3 and t4 are same instance.
               * java.lang.IllegalThreadStateException
               * Second time start called on same instance.
               */
              t4.start();
     


Comments