How to Create and Start Multiple Threads in Java? - Example

Hello guys, Multithreading is one of the biggest strengths of Java, which allows you to divide a task and execute faster by using more than one thread. 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 tasks, you can either use the Runnable or Callable interface. If you are just learning Java chose the Runnable interface, it's a 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 the 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 the Operating system have 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 rare 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 the 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 in 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 the Thread class. This method first creates a thread and then calls the run() method of the Runnable task you have passed to this new thread.

If you directly call the run() method then the code will be executed in the same thread on which you called the run() method, multi-threading or concurrency will not be achieved, as I have explained previously in my article difference between the 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 to this course, which costs around $29 per month or $299 annually (14% discount). 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 the run() method or it came out of the run() method by using the 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 that explains the lifecycle of a thread in Java, you can see different states of thread in Java, and if you want to learn see a threading course like  Multithreading and Parallel Computing in Java from Udemy. It's a great course to learn the multithreading basics and becoming a better Java developer.  


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 the start() method on T1 first. This is the job of the 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 thread in your Java program. Once you learn the 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 multithreading in Java in depth.

Further Learning
Java Concurrency in Practice - The Book
Applying Concurrency and Multi-threading to Common Java Patterns

 Other Java Multithreading and Concurrency Articles you may like
  • 5 Courses to Learn Java Multithreading in-depth (courses)
  • Difference between volatile, synchronized, and atomic variable in Java (answer)
  • 10 Java Multithreading and Concurrency Best Practices (article)
  • Top 5 Books to Master Concurrency in Java (books)
  • How to do inter-thread communication in Java using wait-notify? (answer)
  • How to pause a Thread in Java? (solution)
  • Top 50 Multithreading and Concurrency Questions in Java (questions)
  • How to avoid deadlock in Java? (answer)
  • Difference between CyclicBarrier and CountDownLatch in Java? (answer)
  • Understanding the flow of data and code in Java program (answer)
  • How to join two threads in Java? (answer)
  • Difference between Executor and ExecutorService in Java? (answer)
  • How to stop a Thread in Java? (answer)
  • Difference between ForkJoinPool and Executor Framework in Java(answer)
  • 5 Essential Skills to Crack Java Interviews (skills)
  • What is Happens Before in Java Concurrency? (answer)

Thanks a lot for reading this article so far. If you like this example of creating multiple threads in Java then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

P. S. - If you are serious to improve your Java Multithreading and Concurrency Skills but looking for a free course to start with then I also, suggest you check out this awesome free Java Multithreading course on Udemy. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.