Saturday, August 25, 2012

What is Thread and Runnable in Java - Example

What is Thread in Java
Thread in Java is an independent path of execution which is used to run two task in parallel. When two Threads run in parallel that is called multi-threading in Java. Java is multi-threaded from start and excellent support of Thread at language level e.g. java.lang.Thread class, synchronized keyword, volatile and final keyword makes writing concurrent programs easier in Java than any other programming language e.g. C++. Being multi-threaded is also a reason of Java's popularity and being number one programming language. On the other hand if your program divides a task between two threads it also brings lot of programming challenges and issues related to synchronization, deadlock, thread-safety and race conditions. In short answer of question What is Thread in Java can be given like "Thread is a class in Java but also a way to execute something in parallel independently in Java". Thread in Java requires a task which is executed by this thread independently and that task can be either Runnable or Callable which we will see in next section along with an example of  How to use multiple Thread in Java. Difference between Thread and Runnable in Java is also a popular thread interview question in Java.


What is Runnable in Java
What is Thread and Runnable in Java program
Runnable represent a task in Java which is executed by Thread. java.lang.Runnable is an interface and defines only one method called run(). When a Thread is started in Java by using Thread.start() method it calls run() method of Runnable task which was passed to Thread during creation. Code written inside run() method is executed by this newly created thread. Since start() method internally calls run() method its been a doubt among Java programmers that why not directly call the run() method. This is also asked as what is difference between start() and run() method in Java. Well when you call Runnable interface run() method directly , no new Thread will be created and task defined inside run() method is executed by calling thread.  There is another interface added in Java 1. 5 called Callable which can also be used in place of Runnable interface in Java. Callable provides additional functionality over Runnable in terms of returning result of computation. Since return type of run() method is void it can not return anything which is sometime necessary. On the other hand Callable interface defines call() method which has return type as Future which can be used to return result of computation from Thread in Java.


Thread Example in Java.
Here is a simple example of Thread in Java. In this Java program we create two Thread object and pass them two different Runnable instance which is implemented using Anonymous class in Java. We have also provided name to each thread as “Thread A” and “Thread B”, name is optional and if you don’t give name, Java will automatically provide default name for your Thread like “Thread 0” and “Thread 1”. When we start thread using start() method it calls run() method which has code for printing name of Thread two times for Thread A and three times for Thread B.


/**
 * Java Program to demonstrate how to use Thread in Java with Example
 * Here two threads are provided Runnable interface implementation using
 * anonymous class and when started they will print Thread's name.
 * @author
 */

public class ThraedExample{

    public static void main(String args[]){
       
        //two threads in Java which runs in Parallel
        Thread threadA = new Thread(new Runnable(){
            public void run(){
                for(int i =0; i<2; i++){
                    System.out.println("This is thread : " + Thread.currentThread().getName());
                }
            }
        }, "Thread A");
       
        //Runnable interface is implemented using Anonymous Class
        Thread threadB = new Thread(new Runnable(){
            public void run(){
                for(int i =0; i<3; i++){
                    System.out.println("This is thread : " + Thread.currentThread().getName());
                }
            }
        }, "Thread B");
       
        //starting both Thread in Java
        threadA.start(); //start will call run method in new thread
        threadB.start();
       
    }  

}

Output
This is thread : Thread A
This is thread : Thread A
This is thread : Thread B
This is thread : Thread B
This is thread : Thread B

That’s all on What is Thread in Java, What is Runnable in Java and How to use Thread in Java with Example. Thread is one of the most important concept in Java and must for every Java programmer, it also forms basis of a Java interview. Checkout these 15 Java multi-threading questions and answer to improve your knowledge on Java Threads.

Other Java tutorials you may like :

No comments:

Post a Comment

Java67 Headline Animator