Creating Threads in Java: A Comprehensive Guide

Rumman Ansari   Software Engineer   2024-07-04 04:47:18   7295  Share
Subject Syllabus DetailsSubject Details 6 Questions
☰ TContent
☰Fullscreen

Table of Content:

Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.

How to create thread

There are two ways to create a thread:

  1. By extending Thread class
  2. By implementing Runnable interface.

Thread class:

Thread class provide constructors and methods to create and perform operations on a thread.Thread class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:

  • Thread()
  • Thread(String name)
  • Thread(Runnable r)
  • Thread(Runnable r,String name)

Thread Methods

Following is the list of important methods available in the Thread class.

Sr.No. Method & Description
1

public void start()

Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.

2

public void run()

If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.

3

public final void setName(String name)

Changes the name of the Thread object. There is also a getName() method for retrieving the name.

4

public final void setPriority(int priority)

Sets the priority of this Thread object. The possible values are between 1 and 10.

5

public final void setDaemon(boolean on)

A parameter of true denotes this Thread as a daemon thread.

6

public final void join(long millisec)

The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.

7

public void interrupt()

Interrupts this thread, causing it to continue execution if it was blocked for any reason.

8

public final boolean isAlive()

Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.

9

public void join()

waits for a thread to die.

10

public int getPriority()

 returns the priority of the thread.

11

public String getName()

 returns the priority of the thread.

 12

public int getPriority()

 returns the name of the thread.

 13  

public int getId()

 returns the id of the thread.

 14  

public Thread.State getState()

 returns the state of the thread.

 15  

public void suspend()

 is used to suspend the thread(depricated).

 16  

public void resume()

 is used to resume the suspended thread(depricated).

 17  

public void stop()

 is used to stop the thread(depricated).

18

public boolean isDaemon()

 tests if the thread is a daemon thread.

19

public boolean isInterrupted()

 tests if the thread has been interrupted.

The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread.

Sr.No. Method & Description
1

public static void yield()

Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled.

2

public static void sleep(long millisec)

Causes the currently running thread to block for at least the specified number of milliseconds.

3

public static boolean holdsLock(Object x)

Returns true if the current thread holds the lock on the given Object.

4

public static Thread currentThread()

Returns a reference to the currently running thread, which is the thread that invokes this method.

5

public static void dumpStack()

Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application.

6

public static boolean interrupted()

tests if the current thread has been interrupted.

Runnable interface:

The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. Runnable interface have only one method named run().
  1. public void run(): is used to perform action for a thread.

Some Important points to Remember

  1. When we extend Thread class, we cannot override setName() and getName() functions, because they are declared final in Thread class.
  2. While using sleep(), always handle the exception it throws.
    static void sleep(long milliseconds) throws InterruptedException

Extending Thread class

To create a thread by a new class that extends Thread class and create an instance of that class. The extending class must override run() method which is the entry point of new thread.

class MyThread extends Thread
{
 public void run()
 {
  System.out.println("Concurrent thread started running..");
 }
}

classMyThreadDemo
{
 public static void main( String args[] )
 {
  MyThread obj = new  MyThread();
  obj.start();
 }
}

Output :

concurrent thread started running..

In this case, also, we must override the run() and then use the start() method to run the thread. Also, when you create MyThread class object, Thread class constructor will also be invoked, as it is the super class, hence MyThread class object acts as Thread class object.

Implementing the Runnable Interface

The easiest way to create a thread is to create a class that implements the runnable interface. After implementing runnable interface , the class needs to implement the run() method, which is of form,

public void run()

Starting a thread:

start() method of Thread class is used to start a newly created thread. It performs following tasks:
  • A new thread starts(with new callstack).
  • The thread moves from New state to the Runnable state.
  • When the thread gets a chance to execute, its target run() method will run.
Remember
  • run() method introduces a concurrent thread into your program. This thread will end when run() method terminates.
  • You must specify the code that your thread will execute inside run() method.
  • run() method can call other methods, can use other classes and declare variables just like any other normal method.
class MyThread implements Runnable
{
 public void run()
 {
  System.out.println("concurrent thread started running..");
 }
}

class MyThreadDemo
{
 public static void main( String args[] )
 {
  MyThread mt = new MyThread();
  Thread t = new Thread(mt);
  t.start();
 }
}

Output :

concurrent thread started running..

To call the run() method, start() method is used. On calling start(), a new stack is provided to the thread and run() method is called to introduce the new thread into the program.

Note: If you are implementing Runnable interface in your class, then you need to explicitly create a Thread class object and need to pass the Runnable interface implemented class object as a parameter in its constructor.