Tuesday, December 7, 2010

Start and Run ..... Why do we need both ???

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.

Java Threads - Implements Runnable V/s extends Thread


Java Threads - Implements Runnable V/s extends Thread class

Threads are very important part of any computer system, that wants to do multitasking. Threads are called low-weight processes. A process is a program under execution. Program has a text part, data part. It has memory to use for it's execution. Threads share this memory, so communication between threads is very simple and not costlier compared to IPC.

Java provides support for multi threading and also in java it is very easy to play with them.

The below article is for people who already know how to implement a Thread in java. Java gives users, 2 options. Either they have to implement Runnable interface Or they have to extend from Thread class. Only then any class, say "X" can be Thread scheduled.

Thread scheduler is part of OS and not part of JVM. So the ways threads behave changes from platform to platform.

Why do we have 2 ways of creating Thread classes ?

First thing we have to keep in mind that, Java doesn't support multiple inheritance. i.e, "class A extends B,C" is not true, where as "class A implements B,C" is true.

So if a class X extends Thread, then it cannot extend from any parent (So sad :-( ). In order to avoid this, Runnable interface is defined and it is always better to use interfaces than extending from a parent.