Friday, May 2, 2008

Java difference between thread start vs run methods

It is very impotent to know the difference between thread start run methods. both will executes the same run method. There is some very small but important difference between using start() and run() methods. Look at two examples below:

The result of running examples will be different.

Example : 1

Thread one = new Thread();
Thread two = new Thread();
one.run();
two.run();

In This Example  the threads will run sequentially: first, thread number one runs, when it exits the thread number two starts.

Example : 2

Thread one = new Thread();
Thread two = new Thread();
one.start();
two.start();

In This Example   both threads start and run simultaneously.

Example : 3

public class TesTwo extends Thread {
    public static void main(String[] args) throws Exception{
        TesTwo t=new TesTwo();
        t.start();   
        t.run();
        doIt();       
    }
public void run()

{
    System.out .println("Run");
}
    private static void doIt()

{
        System.out.println("doit. ");
    }
}

Output:

Run
Run
doit.

In this example the start(public void run())  and run methods will executes simultaneously.Because after execution of start statement there are two simultaneous ways.

           t.start(); 

      clip_image002clip_image001

t.run();      public void run()

the two lines will executes simultaneous . so the output will print Run Run in output. after completion of public void run method then controller will return to doIt method. At last the method do It will execute.

Example : 4

public class TesTwo extends Thread {
    public static void main(String[] args) throws Exception{
        TesTwo t=new TesTwo();       
        t.run();
        t.start();
        doIt();       
    }
public void run(){
    System.out .println("Run");
}
    private static void doIt() {
        // TODO Auto-generated method stub
        System.out.println("doit. ");
    }
}

Output:

Run
doit.
Run

In this example the  run method will executes synchronously.so the in output it prints first line  "Run". Next start and doit methods will executes simultaneously.Because after execution of start statement there are two simultaneous ways.

           t.start();  

      clip_image002clip_image001

doIt();      public void run()

the two lines will executes simultaneous . so the output will print " doit. Run" in output second and third line.

Conclusion: The start() method call run() method asynchronously does not wait for any result, just fire up an action), while we run run() method synchronously - we wait when it quits and only then we can run the next line of our code.

Start()--> asynchronous.

run() -->synchronous.

0 comments:

Google