If you remember, a Thread is started in Java by calling the start() method of java.lang.Thread class, but if you learn more you will find out that start() method internally calls the run() method of Runnable interface to execute the code specified in the run() method in the separate thread. Now the question comes, why can't you just call the run() method instead of calling the start() method because anyway start() is calling the run()? This is one of the tricky multi-threading question you will find on Java interviews. The trick here is that, when you directly call the run() method than the code inside run() method will not be executed on a new thread, instead it will be executed on the same thread. On the other hand, when you call the Thread.start() method, then the code inside run() method will be executed on a new thread, which is actually created by the start() method. This is one of the fundamental of threading in Java, which is often get overlooked by Java developers unless you have read book like Java Threads By Scott Oaks, which explains every key multi-threading concept and thread basics in good detail.
Read more »
No comments:
Post a Comment