How to use Multiple Threads in Java - Example

In order to use multiple threads in Java, you need to first define the task which will be executed by those threads. In order to create those task, you can either use Runnable or Callable interface. If you are just learning Java chose Runnable, it's simpler one, but if you are familiar with Java multithreading and want to leverage additional features offered by Callable e.g. it can throw an exception and it can also return value, then go ahead and use Callable. Once you have task ready, you need to create an instance of Thread class. You can create as many instances as you want, but beware don't create too many Thread instances in Java because both JVM and Operating system has a limit on how many threads you can create in Java. Crossing that limit will result in java.lang.OutOfmemoryError: could not create a native thread. For the purpose of this example, creating just three threads are enough.

Let's assume we create threads T1, T2, and T3. While creating we pass them an instance of your Task class, which extends Runnable. Always remember, you cannot pass an instance of any arbitrary class, you must pass either Callable or Runnable. Any code which is written in the run() or call() will then be executed by the thread you passed your task to.

You can read Core Java Volume 1 - Fundamentals by Cay S. Horstmann and Effective Java by Joshua Bloch to learn more about how to achieve effective multithreading





How to start a Thread in Java

Just creating an instance of Thread doesn't start them, you need to start each thread manually by calling Thread.start() method. This method first creates a thread and then call run() method of Runnable task you passed to it in this new thread.

If you directly call run() method then the code will be executed in the same thread on which you called run() method, multi-threading or concurrency will not be achieved.

This is also one of the common mistakes many Java developers make, you can read more about it here.

As I said, you further read Core Java Volume 1 - Fundamentals by Cay S. Horstmann to learn more about Threads in Java. It also covers advanced multi-threading concepts e.g. using concurrency utilities like CountDownLatch, CyclicBarrier or Phaser in Java application.

Java thread example




Java Program to Create and Run a Thread
Here is a Java Program to demonstrate how to use thread by first creating an instance of java.lang.Thread class and later by calling the start method.

/**
 * Simple Java program to demonstrate how to use multiple threads.
 * Steps to use
 * multiple threads in Java : 
 * 1. Implement Runnable interface to put the code
 * you want to run in separate thread. 
 * 2. Create an Instance of Thread class by
 * passing an instance of Runnable you just created. 
 * 3. Call Thread.start()
 * method, this will execute the code in separate thread.
 * 
 * @author WINDOWS 8
 *
 */
public class MultipleThreadDemo {

    private static class ParallelTask implements Runnable {

        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()
                    + " is executing this code");

        }

    }

    public static void main(String[] args) {

        // created three threads but none will start until you call
        // start() method
        Thread t1 = new Thread(new ParallelTask(), "Thread - T1");
        Thread t2 = new Thread(new ParallelTask(), "Thread - T2");
        Thread t3 = new Thread(new ParallelTask(), "Thread - T3");

        // now, let's start all three threads
        t1.start();
        t2.start();
        t3.start();
    }

}


Output
Thread - T1 is executing this code
Thread - T3 is executing this code
Thread - T2 is executing this code


Once a Thread finishes the last line of code inside run() method, or it came out of run() method by using return statement or it came out of run() due to an exception is thrown, the thread is finished. You can not reuse this thread again. Calling the start() method on such thread will result in IllegalThreadStateException.

Here is a nice diagram which explains the lifecyle of a thread in Java:

How to create and run thread in Java


Also, when you start multiple threads at the same time in Java, there is no guarantee that which thread will start execution first. It is possible that T3 starts processing before T1 even when you call start() method on T1 first. This is the job of Thread scheduler.


No comments:

Post a Comment