×

Thread Concept in Java

What is a Thread?

A subprocess that is lightweight in Java is known as a thread. It is the smallest unit of a process. For the running of multiple tasks parallelly we can use threads. Before we were unable to run multiple tasks at the same time. To overcome that drawback, the thread concept was introduced. A thread is similar to a program. It is a subpart of a program. And it has a flow of control.

Thread Concept in Java

As shown in the above figure, inside a process a thread is executed. Inside the OS (Operating system) we will have multiple processes. And inside each process, we will have multiple threads.

Advantages of Threads

  • Threads are independent.
    That means threads have a separate path for execution. If we have an exception in one thread, all the remaining threads are not affected.
  • Threads use a shared memory area.

Java Thread Class

To achieve thread programming, we have a " Thread class " in Java. This Thread class provides many methods as well as constructors to perform and create operations on the thread.

Thread methods in Thread class

Many methods are provided by the Thread class. A few of them are listed below.

S.NoReturn TypeMethod Name               Description
1voidstart()Execution of the thread will start when we use this method.
2voidrun()For doing an action to a thread this method is used.
5intgetPriority()The priority of the thread is returned by this method.
9intgetId()This method gives the ID of the thread as output.
10BooleanisAlive()This method returns true if the thread is alive or else it returns false.
11voidsuspend()A thread is suspended using this method.
12voidresume()To resume the suspended thread, we use this method.
13voidstop()A thread is stopped by using this method.
14voidinterrupt()To interrupt the thread, we use this method.
15BooleanisInterrupted()If a thread is interrupted, then it returns true, or else this method returns false.
16Static Booleaninterrupted()To check whether the current thread is interrupted or not we use this method.
17voidnotify()To notify only one thread that is waiting for a particular object we use this method.
18voidnotifyAll()To notify all the threads which are waiting for particular objects we use this method.

 These are the most used methods of the Thread class.

Constructors of Thread class:

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

The life cycle of a Thread or Thread States

The Thread goes through 5 stages. They are

Stage 1: New

Stage 2: Runnable

Stage 3: Running

Stage 4: Non-runnable

Stage 5: Terminated

But according to Sun, a thread has only four stages that are only new stage, the runnable stage, the non-runnable stage, and terminated stage. There is no running stage in the life cycle of the thread. But for better understanding, we have to use the running stage. The JVM ( Java virtual machine ) controls the entire life cycle of the thread.

By using a figure, we can easily understand the life cycle of a thread.

Thread Concept in Java

Now let us understand each stage clearly,

  1. New
    Before invoking the start() method an instance of a Thread class is created then the Thread is said to be in the new stage.
  2. Runnable
    After the invocation of the start() method, we can say that a thread is in the runnable stage.
  3. Running
    The thread scheduler has selected a thread means it is said to be in the running stage.
  4. Non – Runnable
    This stage can also be called as Blocked stage. At this stage, the thread is not eligible to run currently but is still alive.
  5. Terminated
    This method is also known as the dead stage. When the run() method exists the thread is terminated.

How to create a thread?

Two ways are available to create a thread, they are:

  • By extending the Thread class.
  • By implementing a Runnable interface.

Creation 1

ThreadCreation.java

class ThreadCreation extends Thread
{
public void run() // run method
{
System.out.println(" The thread is running... ");
}
public static void main(String args[])
{
ThreadCreation tc = new ThreadCreation();
tc.start(); // start method
}
}

Output:

Thread Concept in Java

Now let’s understand how to create a thread by implementing a runnable interface by using an example.

ThreadCreation1.java

class ThreadCreation1 implements Runnable
{
public void run() // run method
{
System.out.println(" The Thread is running ... ");
}
public static void main(String args[])
{
ThreadCreation1 tc = new ThreadCreation1();
Thread t1 = new Thread(tc);
t1.start(); // start method
}
}

Output:

Thread Concept in Java

Related Topics

Java Enum

Enumerations are used in programming languages to represent collections of named constants. For instance, the four suits in a deck of playing cards might represent four iterators named Club, Diamond,...

3 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

Java inheritance with Example

Java inheritance Java inheritance is a mechanism in which a child object acquires all the properties and behaviors of a parent object. It helps in reusing the code and establishes...

7 minutes read.

System Class in Java

The System class provides features including a way to load files and libraries, standard input, standard output, and errors throughput streams, accessibility to outside defined characteristics and environment variables, and...

3 minutes read.

Collection Programs in Java

Collection Programs in Java Collection in Java provides a way to manipulate or store a group of objects. Each object in a collection is called element. Collection programs in Java mainly...

4 minutes read.

Java String equalsIgnoreCase() method

equalsIgnoreCase() method compares two Strings based on the their content but ignore the case. Syntax public boolean equalsIgnoreCase(Objects anObject) Parameter anObject: Object to be compared with the current String without case consideration. Returns It returns true...

1 minute read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

Java Return Keyword

The return keyword in Java is used to end a method's execution. the caller receives the return, followed by the appropriate value. The return type of the method, such as...

3 minutes read.

How to download Eclipse for Java

Introduction: We write a java program, and when we want to run it, we need software to run it. Eclipse is a kind of software used to execute a JavaFX...

3 minutes read.

Java Math cbrt() Method

The cbrt() method of Math class returns the cube root of a double value. Syntax: public static double cbrt(double a) Parameters: The parameter ‘a’ represents the value whose cube root is to be determined. Return...

2 minutes read.

Static() Function in Java

The static keyword in Java is suitable for variables, constants, and functions. The static keyword is mainly used to control storage so that it may be appropriately used. We shall...

3 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Java Try-Catch Block

Java Try Block The handling of the exceptions in a block of code is done with the help of java try block. It throws the code that is enclosed in a...

3 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Java Boolean toString() Method

The toString() method of Java Boolean class returns a String corresponding to this Boolean object. It returns a string value “true”, if the defined object is true else it returns...

2 minutes read.

Java Math ceil() Method

The ceil() method of Math class returns the smallest double value which is closest to negative infinity and is greater than or equal to the argument. Syntax: public static double ceil(double a) Parameters: The...

2 minutes read.

Sylvester Sequence in Java

A Sylvester Sequence is a series of numbers in which each term is the sum of the terms before it plus 1. The sequence's first two terms are 2 and...

3 minutes read.

Automatic Resource Management

In computer programming, resource management refers to the wide set of techniques for the effective management of the system resources. There are two ways of management of resources: The computer program itself...

2 minutes read.

Tribonacci series in Java

The Fibonacci series and the Tribonacci sequence are linked. The Fibonacci sequence, each element summates the three preceding terms, is expanded into the Tribonacci series in Java. Through specific examples,...

3 minutes read.