Matt Choi Matt Choi - 3 months ago 12
Java Question

How many threads are there here?

public Demo implements Runnable(){
private String threadName;
public Thread t;

public Demo(String name){
this.threadName = name;
}

public void begin(){
t = new Thread(this,threadName);
t.start();
}

public void run(){
Thread.sleep(1000);
System.out.println("Running");
}
}

public static void main(String args[]) {
Demo demo1 = new Demo("DEMO1");
demo1.begin();
Demo demo2 = new Demo("DEMO2");
demo2.begin();
}


Okay, I am a little confused about Thread even after reading API and documentations. My understanding is that, if you either implement Runnable() or extend Thread class, it creates its own thread.

So in this case,
The Public static void main() creates the "Main Thread", then its children are the 2 subsequent threads (Demo objects), and after calling "begin()", there are another 2 threads stemming from Demo objects.


  1. There are 5 threads in this code?

  2. Thread.sleep(1000) seem to stop all of the threads, thus it is referring to the "Main Thread"?

  3. If I call synchronized(this) in run() method inside Demo class, Demo1 has owns its monitor at the same time Demo2 owns its monitor, doing its own task simultaneously? Or because they share one common "Main Monitor", they go execute one at a time, waiting in queue.


Answer

Calling start() on a Thread object starts a new thread. A plain Runnable does not create new threads, only Thread objects do.

There are 5 threads in this code?

There are three threads.

Thread.sleep(1000) seems to stop all of the threads.

It's called from the two new threads and delays them for one second.

The reason the entire program appears to stop is that a program doesn't terminate if there are other active threads (unless those threads are daemon threads, which these aren't). The main thread will have already exited, but the existence of your two extra threads will cause the program to continue running until those threads have finished.

If I call synchronized(this) in run() method inside Demo class, Demo1 has owns its monitor at the same time Demo2 owns its monitor, doing its own task simultaneously?

Threads will only block if they synchronize on the same object. this refers to two different objects, so the threads will not block each other.

Comments