I have a problem with understanding this code. I have only a couple of hours' knowledge of Java.
Here is the code :
// Create a new thread.
class NewThread implements Runnable {
Thread t;
NewThread() {
// Create a new, second thread
t = new Thread(this, "Demo Thread");
System.out.println("Child thread: " + t);
t.start(); // Start the thread
}
// This is the entry point for the second thread.
public void run() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Child Thread: " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Child interrupted.");
}
System.out.println("Exiting child thread.");
}
}
public class ThreadDemo {
public static void main(String args[]) {
new NewThread(); // create a new thread
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(100);
}
} catch (InterruptedException e) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
And here is output of it :
Child thread: Thread[Demo Thread,5,main]
Main Thread: 5
Child Thread: 5
Child Thread: 4
Main Thread: 4
Child Thread: 3
Child Thread: 2
Main Thread: 3
Child Thread: 1
Exiting child thread.
Main Thread: 2
Main Thread: 1
Main thread exiting.
Here are my questions.
I want to understand the pattern the code follows. According to me,
main()
function. So, instance of NewThread should be initialized.Child thread: Thread[Demo Thread,5,main]
public void run()
(AM I WRONG HERE ?? )In public void run()
, I think I should have gotten an output Child Thread 5
, but instead I got Main Thread 5
. I wonder why ??
Is there anyone to help me ?? Thanks in advance.
t.start()
creates a new thread, and calls run()
from that. At that point, there are two threads running independently: the one that called start()
, and the new one. The original thread returns from the constructor and then starts executing the loop in the main()
method.
As the two threads are independent, there's no guarantee which thread will reach a call to System.out.println
first. In the sample output that you've given, it so happens that the original thread gets to print first. It could easily happen the other way round though.
As an aside, if you're new to Java I would suggest you learn the basics of the language before you get to threading. There's nothing in your question which indicates that you're confused, but threading is a relatively advanced topic, and it's worth being comfortable with the general language behaviour before you get that far, IMO. That way you can be confident that any odd behaviour you see really is due to threading and not to misunderstanding other parts of the language.
See more on this question at Stackoverflow