How to use Multiple Threads in Java - Example

Hello guys, Multithreading is one of the biggest strength of Java, which allows you to divide a task and execute faster by using more than one threads. 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 the Runnable interface, it's simpler one, but if you are familiar with Java multithreading and want to leverage additional features offered by Callable like it can throw an exception and it can also return value, then go ahead and use the Callable interface. Once you have task ready, you need to create an instance of the Thread class.

You can create as many instances as you want, Java will allow that, but you should be aware of your resources. Generally, you shouldn'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 an error like java.lang.OutOfmemoryError: could not create a native thread, which is rate but quite possible in a highly multi-threaded environment like a web server.

Btw, for the purpose of this tutorial and 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 an 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. The key thing to note is that the thread which passes the code is different than the thread which executes the code. This is where multiple threads come into the picture.

Btw, you can also use thread pools to create multiple threads but that's a little bit advanced topic and we'll discuss into some other article but if you are curious you can join a comprehensive course like The Complete Java MasterClass  to learn more about how to achieve effective multithreading




How to start a Thread in Java

You might already know that just creating an instance of java.lang.Thread class doesn't start a new thread, you need to start each thread manually by calling the start() method of Thread class. This method first creates a thread and then call the run() method of Runnable task you have passed to 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, as I have explained previously on my article difference between start and run method of thread in Java.

This is also one of the common multi-threading mistakes many Java developers make. As Brian Goetz has right put that creating a concurrent application is never easy despite the best effort of library, frameworks, and Java programming language itself.

As I said, you further join a Java multithreading course like Java Fundamentals - Concurrency with Multithreading on Pluaralsight to learn more about Threads in Java. It also covers advanced multi-threading concepts like thread pools and how to use concurrency utilities like CountDownLatch, CyclicBarrier or Phaser in Java application.

How to use Multiple Threads in Java - Example


Btw, you would need a Pluralsight membership to get access this course, which cost around $29 per month or $299 annually (14% discount).

If you don't have Pluralsight membership, I encourage you to get one because it allows you to access their 5000+ online courses on all latest topics like front-end and back-end development, machine learning etc. It also includes interactive quizzes, exercises, and latest certification material.

It's more like Netflix for Software Developers and Since learning is an important part of our job, Plurlasight membership is a great way to stay ahead of your competition.

They also provide a 10-day free trial without any commitment, which is a great way to not just access this course for free but also to check the quality of courses before joining Pluralsight.



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.

As you might already know that 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 lifecycle 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.

That's all about how to use multiple threads in Java. As I said, there are many ways but this is the simplest way to use more than one threads in your Java program. Once you learn basics, you can explore more advanced topics like thread-pool which is a more standard and sophisticated way to leverage multiple threads for processing data in Java program.

If you want to learn more here are some useful resources to learn multi-threading in Java in depth.

Further Learning
The Complete Java Masterclass
Applying Concurrency and Multi-threading to Common Java Patterns
Java Concurrency in Practice - The book
Java Concurrency in Practice Course by Heinz Kabutz
50+ Java Multithreading Interview Questions in Java
How to avoid deadlock in Java programs
Top 5 Courses to Learn Multithreading and Concurrency in Java
Multithreading and Parallel Computing in Java

Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any questions or feedback then please drop a note.

No comments:

Post a Comment