1
public class SingletonClass {
private static SingletonClass singletonClass;
public void executeMethod(String string) {
    System.out.print("["+string);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("]");
}
private SingletonClass() {

}
public static SingletonClass getInstance() {
    if(singletonClass==null)
        singletonClass=new SingletonClass();
    return singletonClass;
}

public static void main(String args[]) {
    SingletonClass.getInstance().executeMethod("MainThread");
    new SingleTonThread(SingletonClass.getInstance());
}

}

class SingleTonThread implements Runnable{
private SingletonClass sc;
SingleTonThread(SingletonClass singleton){
    this.sc=singleton;
    Thread t = new Thread(this);
    t.start();
}
@Override
public void run() {
    sc.executeMethod("SingleTonThread");
}

}

I expected following output (as main thread should be preempted by SingleTonThread) : expected Output: [MainThread[SingleTonThread] ] Actual output : [MainThread] [SingleTonThread]

jayanth
  • 85
  • 8
  • 1
    You finish executing `executeMethod("Main Thread")` - sleep and all - before you even start the other thread. – Andy Turner Jun 04 '18 at 18:17

1 Answers1

3

When calling:

SingletonClass.getInstance().executeMethod("MainThread");

you have blocked the main thread by calling

sleep(1000)

The following line that initiate the thread class will not be executed until

executeMethod("MainThread")

Will finish to execute

By the way it is a very bad practice to start a thread in a constructor as described in this question

Oz Molaim
  • 2,016
  • 4
  • 20
  • 29