Friday, January 4, 2008

Diff between calling a start()->run() method AND calling run() method directly without start() method

If the run() method of a Thread is called directly without start() method. It fails to obey properties of Thread. It acts as a normal method.

Example: without using start()

 class ThreadA extends Thread { 
ThreadA() {
}

public void run() {
for (int i = 0; i < 5; i++) {
System.out.println("I am in run method " + i + " " + this.getName());
try {
this.sleep(500);
} catch (InterruptedException ie) {
System.out.println(ie);
}
}
}
}

public class Threadtest {
public Threadtest() {
}

public static void main(String[] args) {
Thread t1 = new Thread(new ThreadA(), "t1");
Thread t2 = new Thread(new ThreadA(), "t2");
t1.run();
t2.run();
}
}

The output will be:
I am in run method 0 Thread-0
I am in run method 1 Thread-0
I am in run method 2 Thread-0
I am in run method 3 Thread-0
I am in run method 4 Thread-0
I am in run method 0 Thread-1
I am in run method 1 Thread-1
I am in run method 2 Thread-1
I am in run method 3 Thread-1
I am in run method 4 Thread-1

But,
if the lines t1.run() and t2.run() are replaced by t1.start() and t2.start() then the output is,

I am in run method 0 Thread-0
I am in run method 0 Thread-1
I am in run method 1 Thread-1
I am in run method 1 Thread-0
I am in run method 2 Thread-0
I am in run method 2 Thread-1
I am in run method 3 Thread-1
I am in run method 3 Thread-0
I am in run method 4 Thread-0
I am in run method 4 Thread-1

1 comment:

Parameswaran said...

really u r having very nice blog over here..

BY Parames.