Difference between Thread start() and Runnable run()

UPDATED: 02 August 2016
Lets first understand run() method of Runnable. Consider following code snippet.

Source code (Car.java)
public class Car implements Runnable{

    @Override
    public void run() {
        System.out.println("Run car...");
    }
}
Source code (Cycle.java)
public class Cycle{

    public void run() {
        System.out.println("Run cycle...");
    }
}
public class Test {
    public static void main(String[] args) {
        /* Calling method of class Cycle */
        new Cycle().run();
        /* Calling method of class Car, doesn't matter class implements Runnable */
        new Car().run();
    }
}
There is no difference between new Cycle().run() and new Car().run() even if Car implements Runnable . You are just calling method of class Car.

Runnable in Thread
public class Test {
    public static void main(String[] args) {
        Thread thread = new Thread(new Car());
        /* It'll start new Thread and call run method of Car() in Thread environment */
        thread.start();
    }
}
run method of Car will be executed in separate Thread environment. thread.start() will start new Thread.

Conclusion
- run method of Runnable will be executed as normal method of class.
- start method of Thread starts the new Thread.

0 comments :