ContactUs :

Please send your Questions & Answers or Feedback to "mohan@javabook.org"

Difference between start and run method in Thread

Main difference is that when program calls start() method a new Thread is created and code inside run() method is executed in new Thread while if you call run() method directly no new Thread is created and code inside run() will execute on current Thread.

 

public class StartVsRunCall{

 

    public static void main(String args[]) {

       

        //creating two threads for start and run method call

        Thread startThread = new Thread(new Task("start"));

        Thread runThread = new Thread(new Task("run"));

       

        startThread.start(); //calling start method of Thread - will execute in new Thread

        runThread.run();  //calling run method of Thread - will execute in current Thread

 

    }

 

    /*

     * Simple Runnable implementation

     */

    private static class Task implements Runnable{

        private String caller;

       

        public Task(String caller){

            this.caller = caller;

        }

       

        @Override

        public void run() {

            System.out.println("Caller: "+ caller + " and code on this Thread is executed by : " + Thread.currentThread().getName());

           

        }        

    }

}

 

Output:

Caller: start and code on this Thread is executed by : Thread-0

Caller: run and code on this Thread is executed by : main

Related Posts Plugin for WordPress, Blogger...
Flag Counter