Wednesday, April 20, 2022

How to Create, Start, and Stop a New Thread in Java? [Example Tutorial]

One of the most important tasks for a Java developer is to learn multi-threading and learn it correctly. There are more Java developers who know multi-threading incorrectly than the programmer who doesn't know at all. In order to learn it correctly, you need to start it from scratch, means the most fundamental concepts of multithreading like how to create create, start, and stop a new thread in Java. I am sure you already know that as you have done that a lot of time but it's worth remembering few facts to not repeat the mistakes many programmers do when they write multithreading code in Java. 

In this article, we'll see a couple of those, mainly while creating, starting, and stop threads in Java. So fasten your seatbelt and let's go a little deep into threads in Java.


1. Use start() instead of run()

start creates a new thread and then execute the code on that thread while run just execute the code in the thread which calls the run() method.  I have discussed this already. See this article for a complete discussion.


2. Use Runnable instead of Thread

There are two ways to create a Task for the thread, something which can be executed in parallel, either by implementing the Runnable interface and overriding the run() method or by extending the Thread class and putting your code inside the run() method there. 

Don't get confused between these two run() methods they are the same Since Thread implements the Runnable interface it gets it from there.

An Example of Creating and Starting Thread in Java

import java.util.Arrays;

public class ThreadBasics{

    public static void main(String args[]) {

        // instance of Runnable implementation for threads
        ParallelTask task = new ParallelTask();
     
     
        // This will only create instance of Thread class
        // it will not start until you call start() method
        Thread T1 = new Thread(task);
        Thread T2 = new Thread(task);
     
        // Starting T1 and T2 thread
        T1.start();
        T2.start();  
   
    }
 
}

/*
 * Always use Runnable to put code which you want to execute parallel
 * Using multiple threads.
 */
class ParallelTask implements Runnable{

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

Output
Thread-0 is executing ParallelTask
Thread-1 is executing ParallelTask



How to create Daemon Thread in Java

There are two kinds of threads in Java, user thread or daemon thread. Some people also like to say daemon or non-daemon. The difference between a daemon and a user thread is that a user thread runs until the run() method completes either normally or due to any Exception and prevents your Java application from exiting.

On the other hand, the daemon thread will not keep your Java program alive if all user threads already finished execution. As soon as the last user thread completes its execution, the daemon thread dies, even if they are executing code in their run() method.

By default any thread, it derives its daemon status from the thread which creates it, that's why any thread created by the main thread is always non-daemon, unless and until you make it daemon explicitly by calling the setDaemon() method.

to give you an example let's modify the earlier example to introduce a 3-second sleep in the run() method of ParallelTask class, this will prevent make thread from running for a longer duration. If both T1 and T2 are non-daemon user threads then your Java program will not terminate until T1 and  T2 finish execution.

On the other hand, if you make them daemon, your Java program will finish as soon as your main thread finishes. Here is the screenshot which will make things clear.

It will even print the following lines before the Java program finishes but in the case of the daemon thread, the program will be abruptly terminated and print statements from T1 and T2 will not be printed.



Main Thread is finished
Thread-1 is finished
Thread-0 is finished


Right Way to Create, Start and Stop a New Thread in Java





Use Volatile variable to Stop Thread in Java

Unfortunately, there is no direct way to stop the thread in Java. There was a stop() method in java.lang.Thread class but it was long deprecated. This means the only way to stop a thread is to ask him to come out from its run execution is to get

Some best practices which will help you to write better multi-threading code
1. Always Name your Thread
2. Prefer Thread Pool vs Thread

That's all about how to create, start and stop a new thread in Java.  You can run this code example in your favorite Java IDE or right from the command prompt to learn more. 

No comments:

Post a Comment

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