This post is about Java Threads. Usual way of starting a Thread ( As all the Java books mention ), is to call start() method on a Thread object. Consider the following code
public class ThreadExample
{
class ThreadImpl implements Runnable
{
public void run()
{
System.out.println("Inside run method");
}
}
public static void main(String[] ar)
{
Thread t1 = new Thread(new ThreadImpl (),"T1");
Thread t2 = new Thread(new ThreadImpl (),"T2");
t1.run(); // This code doesn't start the Thread, instead calls the method run() on "t1".
t2.run();
}
}
Here, instead of t1.start(), we have used t1.run().
When start() method is called Thread is created by the underlying platform and scheduler takes care of all such Threads now on. But when we call run(), it is just another method on a Java object and is not given to Thread scheduler.
Conclusion: If you want to write a multithreaded program, then always use start() method, else you can use run().
Proof for above statement: According to Thread design document by ORACLE (Sun), A Thread in the DEAD state can never go back to RUNNABLE state. That means, it is impossible to call start() method twice on a Thread, as shown below.
Thread t2 = new Thread(new ThreadImpl (),"T2");
t2.start();
t2.start(); // Throws an Exception,as Thread cannot go to RUNNABLE from DEAD state.
Where as, run() method can be called as many times as you want like any other method.
Hence Proved.
Tuesday, December 7, 2010
Subscribe to:
Post Comments (Atom)
Damn. How many people have I seen in recent times do this the wrong way! Sir you opened my eyes :)
ReplyDelete