Reputation: 3022
public static void main(String[] args) throws Exception {
new Thread(new Runnable() {
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Hello");
}
}
}).run();
System.out.println("Bye");
}
In the main thead, I create a new thread, which will print "hello" every second. Why the final "Bye" never got print? In the other word, why the child thread blocks the main thread?
Upvotes: 1
Views: 802
Reputation: 2798
Because you are calling run()
, instead of start()
.
You must never call run()
directly. If you call start()
, the program will call run()
for you, in a different thread. (Like you wanted.) By calling run()
yourself, you are going into the run()
method with the parent thread, and get stuck in an eternal loop, with your parent thread.
Upvotes: 9