Sunday, February 16, 2020

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

One of the most important task 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, I mean 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 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 Runnable interface and overriding run() method or by extending Thread class and putting your code inside run() method there. Don't get confused between these two run() method they are 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. Difference between a daemon and a user thread is that a user thread runs until the run() method completes either by normally or due to any Exception and prevents your Java application from exiting.

On the other hand, daemon thread will not keep your Java program alive if all user threads already finished execution. As soon as last user thread completes its execution, 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 running from 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 Java program finishes but in case of daemon thread, the program will be abruptly terminated and print statements from T1 and T2 will not be printed.

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Prep, Oracle Java Exam Prep

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

Oracle Java Tutorial and Material, Oracle Java Learning, Oracle Java Prep, Oracle Java Exam Prep

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 it's run execution is to get

Related Posts

0 comments:

Post a Comment