×

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

HttpURLConnection

HttpURLConnection Protocol It is a standard set of rules that allow electronic devices to communicate with each other. The http protocol The http protocol is for data communication, distributing, collaborating, hypermedia information systems, on the World Wide...

5 minutes read.

Hierarchy of operators in Java

Operators are the most frequently used terminology in any area of programming, and it helps in various approaches to efficiently solve daily life problems by computer programming. The simple addition of...

4 minutes read.

Java String Matches vs Contains

String Matches in Java The matches() function and its variations are used to determine whether or not a provided text matches a regular expression. The functioning as well as output of...

3 minutes read.

Internal Working of ArrayList in Java

Java's version of a resizable array is called ArrayList. The dynamic growth of an array list ensures that there is always room for new elements. ArrayList's backing data structure is...

8 minutes read.

Java Swing

Java Swing is the extension of Abstract Windows Toolkit (AWT). Any component designed in Swing will appear the same on any platform. Problems/Disadvantage of Abstract Windows Toolkit (AWT): As we know that...

27 minutes read.

Java Thread Priority in Multithreading

As we realise, java, being object-situated, works inside a multithreading climate in which the string scheduler relegates the processor to a string in light of the need for a string....

6 minutes read.

List all files in a Directory in Java

The list of all files in the directory can be done using Java. You should be aware that a directory may include a subfolder and that subdirectory may also contain some...

3 minutes read.

Web Crawler in Java

In this article, you will be acknowledged with what a web crawler in java is and what are its functions. You will also be able to understand where to implement...

4 minutes read.

Upcasting and Downcasting in Java

Type casting in Java is an important and very interesting topic to deal with. But here upcasting and downcasting is somewhat related to typecasting. In normal typecasting, we convert from...

6 minutes read.

Shift right zero Fill Operator in Java and Operator Shifting

Left shift operator ( << ) : The left shift operator is an operator which performs its action at the bits level of a binary Operator. That means when you perform...

4 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

Adapter class in Java

By using the adapter classes, we can implement Listener interfaces. With the help of adapter classes, we can save code as it provides all implementation methods of listener interfaces Advantages of...

3 minutes read.

Special Operators in Java

An operator in Java is a special symbol. It is used to perform operations on two or more variables.  We all know basic operations in Java. There are 8 types...

5 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

Methods in Java

The Methods in Java are the collection of statements that are executed when the method is called. By using the methods, the complexity of writing the code decreases. The method consists...

4 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

Difference between String Tokenizer and split Method in Java

Introduction Today, let us understand the difference between String Tokenizer and Split Method. First, let us learn about the String Tokenizer and Split method individually and then know about their differences String...

7 minutes read.

CRC Program in Java

The acronym CRC stands for Cyclic Redundancy Check. It is invented by W. Wesley Peterson in 1961. It is an error detection technique that detects errors in digital networks (also...

5 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.