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.
- There are 5 threads in this code?
- Thread.sleep(1000) seem to stop all of the threads, thus it is referring to the "Main Thread"?
- 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.