×
☰ See All Chapters

Multithreading - How to create thread in Java

A thread is defined as a separate path of execution inside any process. It is done to use CPU idle time. A process consists of the memory space allocated by the operating system that can contain one or more threads. A thread cannot exist on its own; it must be a part of a process. Whenever a thread is created within a program it will not occupy any separate space. It will share the same memory space of the program. It will also not consume more resources.

multithreading-in-java-0
 

How many threads can a process have?

  1. As many threads as it can handle in its memory space. I have seen applications with thousands of threads. Of course, these applications were running on large servers with lots of memory and multiple CPUs. 

  2. A process can have multiple threads that are runnable at the same time. However, the number of threads actually running at any given time is dependent on the number of CPUs (processors) available. If there is only one CPU then there can be only one thread running. 

  3. Other threads are still runnable, but they are waiting in a queue for the thread scheduler (which is really the JVM) to schedule CPU time for them. For example, suppose that you have two processes and each process has two threads. If one CPU is available, then only one of those threads can be executing at a time, and the other three are waiting. 

  4. Thread scheduler follows particular thread scheduling policy (Round robbin, Preority based..) which depends on platform/Environment. 

  5. In real time we feel CPU executing multiple processes (multiple threads) simultaneously, this is because of context switching (thread switching) which switches from one thread to another very quickly that we cannot notify at all. 

Thread in Java

To write a thread in Java we have to implement Runnable interface, either you write a class that implements Runnable, or you extend a class that already implements Runnable. (Both the Thread and TimerTask classes implement Runnable.) In either case, you define the one method in Runnable:

    public void run()

The body of the run() method is the path of execution for your thread. When the thread starts running, the run() method is invoked, and the thread becomes dead when the run() method runs to completion.

Just by implementing Runnable class we can create thread, but to start the thread we have to associate an instance of implementing class with a java.lang.Thread object.

The purpose of the Runnable class is to separate the Thread object from the task it is performing.  When the Thread object is actually running, the run() method of the Runnable object is the code that executes.

Creating a Thread

SUN has provided 2 different ways to create the child threads:

  1. By extending class Thread. 

  2. By implementing interface Runnable. 

Note: In both the cases you override the run() method and write your logic inside that method you want to execute in a separate thread. The run() method can call other methods, create objects, etc.

By implementing interface Runnable.

Step 1: Write a class by implementing interface Runnable and define the thread by overriding run() method.

class MyRunnable implements Runnable {

        public void run() {

                System.out.println("Child thread executing");

        }

}

Step 2: Create an instance of the Runnable object.

MyRunnable mr = new MyRunnable();

Step 3: Create a thread by passing the runnable object to the constructor of Thread class.

Thread t = new Thread(mr);

Thread will enter into “new state”. A thread in “new state” is not considered to be alive.

Step 4: Start the thread by calling the start() method.

t.start();

When you call the start() method then new thread will create a separate call stack and move from “new state” to “runnable state”. A thread in “runnable state” is considered to be alive.

class DisplayMessage implements Runnable {

        private String message;

 

        public DisplayMessage(String message) {

                this.message = message;

        }

 

        public void run() {

                while (true) {

                        System.out.println(message);

                }

        }

}

 

public class ThreadDemo {

        public static void main(String[] args) {

                System.out.println("Creating the hello thread...");

                DisplayMessage hello = new DisplayMessage("Hello");

                Thread thread1 = new Thread(hello);

                System.out.println("Starting the hello thread...");

                thread1.start();

                System.out.println("Creating the goodbye thread...");

                DisplayMessage bye = new DisplayMessage("Goodbye");

                Thread thread2 = new Thread(bye);

                System.out.println("Starting the goodbye thread...");

                thread2.start();

        }

}

Output:

multithreading-in-java-1
 

Comments about the ThreadDemo program:

  • Two Runnable objects are instantiated: hello and goodbye. 

  • Each of the two Runnable objects is associated with a Thread object: thread1 and thread2. 

  • Invoking start() on the Thread objects causes the thread to become runnable. 

  • When the thread gets scheduled, the run() method on the corresponding Runnable object is invoked. 

  • Just after thread2 is started, there are three threads in this process: the main() thread, thread1, and thread2. 

  • The program does not terminate, even though main() runs to completion. Once main() is done executing, the process still has two non-daemon threads: thread1 and thread2. The process does not terminate until both of these threads finish executing. 

  • That being said, this process never terminates because the two threads do not stop (their corresponding run() methods contain infinite loops). To stop this process, you need to stop the JVM process. (In Windows, press Ctrl+c at the command prompt.) 

By extending class Thread

Following are the steps to create and execute a thread when you extend class Thread.

Step 1: Write a class by extending class Thread and define the thread by overriding run() method.

class MyThread extends Thread { // define a thread

        public void run {

                System.out.println("Child thread executing");

        }

}

Step 2: Create a thread by instantiating that class.

MyThread mt = new MyThread();()// create a thread

Thread will enter into “new state”. A thread in “new state” is not considered to be alive.

Step 3: Start the thread by calling the start() method.

mt.start(); // start threads

When you call the start() method then new thread will create a separate call stack and move from “new state” to “runnable state”. A thread in “runnable state” is considered to be alive.

class DisplayMessage extends Thread {

        private String message;

 

        public DisplayMessage(String message) {

                this.message = message;

        }

 

        public void run() {

                while (true) {

                        System.out.println(message);

                }

        }

}

 

public class ThreadDemo {

        public static void main(String[] args) {

                System.out.println("Creating the hello thread...");

                DisplayMessage hello = new DisplayMessage("Hello");

                System.out.println("Starting the hello thread...");

                hello.start();

                System.out.println("Creating the goodbye thread...");

                DisplayMessage bye = new DisplayMessage("Goodbye");

                System.out.println("Starting the goodbye thread...");

                bye.start();

        }

}

Output:

multithreading-in-java-2
 

Which is the better way of creating a thread? By extending class Thread or by implementing interface Runnable?

It is not good to write a thread by extending class Thread because:-

  • If you extend class Thread then you will inherit all the super class functionality into your subclass which might become an overhead. 

  • You also cannot extend another class. 

  • According to OOP you are tightly coupling two things, the thread and the business logic which is a bad design. 

  • It is good to write a thread by implementing interface Runnable because:- 

  • You can extend another class.  

  • You are decoupling both the thread and the business logic which is a very good design. 

After a thread completes execution, can it be restarted by again calling call the start() method ?

No, once a thread has been started, it cannot be restarted again. If you call the start() method again it will cause IllegalThreadStateException. Once the run() method of a thread completes execution, then the thread moves into the dead state and the call stack is removed. You can always start a new thread only once. A runnable thread or a dead thread cannot be started again.

Who invokes the run() method?

The JVM thread scheduler implicitly invokes the run() method when it decides to execute a thread and moves the new thread from “runnable state” to “running state” . This method will execute in a separate call stack after the thread is started.

Can the run() method be called explicitly by you?

Yes, but it will execute as a normal method and it will never create a separate call stack or it will not start a new thread of execution. It will execute like a normal method in the same stack you are invoking.

What is “inline thread”?

Creating an anonymous class extending Thread and calling its start method in the same line of code.

(new Thread() {

        public void run() {

                        // thread code

        }

}).start();

How to get reference to the currently executing thread object?

The currentThread() method returns a reference to the currently executing thread object

class ThreadDemo extends Thread {

        public void run() {

                System.out.println(Thread.currentThread().getName());

        }

 

        public static void main(String args[]) {

                ThreadDemo t1 = new ThreadDemo();

                ThreadDemo t2 = new ThreadDemo();

                t1.start();

                t2.start();

        }

}

Output:

Thread-0

Thread-1

What is Daemon Thread?

There are two types of threads user thread and daemon thread. The daemon thread is a service provider thread. It provides services to the user thread. Its life depends on the user threads i.e. when all the user threads dies, JVM terminates this thread automatically.

Example: Garbage Collector

Points to remember for Daemon Thread:

  • It provides services to user threads for background supporting tasks. It has no role in life than to serve user threads. 

  • Its life depends on user threads. 

  • It is a low priority thread. 

Why JVM terminates the daemon thread if there is no user thread remaining?

The sole purpose of the daemon thread is that it provides services to user thread for background supporting task. If there is no user thread, why should JVM keep running this thread? That is why JVM terminates the daemon thread if there is no user thread.

What are the methods used to handle Daemon thread?

The java.lang.Thread class provides two methods related to daemon thread

public void setDaemon(boolean status): is used to mark the current thread as daemon thread or user thread.

public boolean isDaemon(): is used to check that current is daemon.

class ThreadDemo extends Thread {

        public void run() {

                System.out.println("Name: " + Thread.currentThread().getName());

                System.out.println("Daemon: " + Thread.currentThread().isDaemon());

        }

 

        public static void main(String[] args) {

                ThreadDemo t1 = new ThreadDemo();

                ThreadDemo t2 = new ThreadDemo();

                t1.setDaemon(true);

                t1.start();

                t2.start();

        }

}

Output:

Name: Thread-1

Name: Thread-0

Daemon: true

Daemon: false

How to check whether thread is alive?

Using isAlive() method.

A thread is considered to be alive when its start() method has been called. After the run() method finishes, the thread is considered to not be alive anymore. We can determine if a thread is currently alive or not by calling a Thread instance's isAlive() method. 

The isAlive( ) method  returns true if the thread  upon which it is called is alive. It returns false otherwise.

class ThreadDemo extends Thread {

        public void run() {

                for (int i = 1; i < 4; i++) {

                        try {

                                Thread.sleep(500);

                        } catch (InterruptedException e) {

                                System.out.println(e);

                        }

                        System.out.println(i);

                }

        }

 

        public static void main(String args[]) throws Exception {

                System.out.println("Inside main");

                ThreadDemo t1 = new ThreadDemo();

                t1.start();

                System.out.println(t1.isAlive());

                t1.join();

                System.out.println(t1.isAlive());

                System.out.println("Leaving main");

                System.out.println(t1.isAlive());

        }

}

Output:

Inside main

true

1

2

3

false

Leaving main

false

 


All Chapters
Author