The Java programming language sustains multi-threaded programs, which implies we can devise multi-threaded applications employing Java. Multiple-threaded programs operate numerous CPUs to manage distinct tasks simultaneously and take full benefit of the available resources, mainly when numerous CPUs are present.
Utilizing multi-threading, you can split particular operations within an application into distinct threads to expand the concept of multitasking. There is no limitation on the number of threads that can be operating simultaneously. Not merely does the OS divide the processing period among different applications, but it does so within each application thread as well.
With multi-threading, you can write programs that can maintain multiple chores simultaneously.
How to Start a Thread in Java
Initially, a thread is initiated by using the start() method of the Thread class. The following are the operations it performs:
- The new thread (with the new call stack) is started.
- In the New state, the thread moves to the Runnable state.
- It is only when the thread has an opportunity to execute that the run() method will be conjured.
It is conceivable to specify what code should be conducted by the Thread in two manners. You can override the run() method by constructing a subclass of Thread. The second method employs a Runnable object (java.lang.Runnable) passed to the Thread constructor. Both methods are exemplified below.
- Overriding a Thread’s run() method is the foremost step in determining what code runs on a thread. After calling start(), the thread directs the run() method. Upon starting the thread, start() returns. As long as the run() method is not yet done, it will not wait. As if run() were performed by a separate CPU, the run() method will manage. Upon execution, the run() method will portray the text “My thread is running.”
- Constructing a class that enforces the java.lang.Runnable interface is another way to define what code a thread should execute. Java threads can run objects that enforce the Runnable interface. With the Java platform, the Runnable interface is a typical Java interface. There is solely one method run() in the Runnable interface.
How to Use a Thread in Java
Use of Thread in Java: The use of threads facilitates a program to operate multiple tasks at the exact time, which makes it more efficient. It is feasible to perform complex tasks in the background without interrupting the central application by using threads.
Technically, Thread is a framework that authorizes Java programs to operate in parallel. The Thread class has a number of commonly used constructors:
- Thread()
- Thread(String name)
- Thread(Runnable r)
- Thread(Runnable r, String name)
The Thread class has the following methods that are commonly used
- public void run(): performs thread-specific actions.
- Public void start(): initiates thread execution. JVM calls the run() method on the thread.
- public void sleep(long milliseconds): Sleeps (temporarily ceases execution) the currently executing thread.
- public void join(): waits until a thread dies.
- public void join(long milliseconds): Detects when a thread has died.
- public int getPriority(): Displays the thread priority.
- public int setPriority(int priority): adjusts thread priority.
- public String getName(): Displays the thread name.
- public void setName(String name): renames the thread.
- public Thread currentThread(): gives the reference to the thread that is currently executing.
How to Create Multiple Threads in Java
The multithreading characteristic of Java permits several parts of a program to operate concurrently so that the CPU can be operated as efficiently as possible. A thread is a fragment of such a program. Processes consist of threads, which are lightweight processes.
Two mechanisms are general for creating threads:
- Extending the Thread class
- Implementing the Runnable Interface
Extending the Thread Class to Create a Thread
We extend the Thread class in java.lang.Thread. A run() method is available in the Thread class that is overridden by this class. The run() method is where a thread initiates its life. The thread execution is created by forming an object of our new class and calling its start() method. The start() method conjures the thread’s run() method.
// Java code for thread creation by extending // the Thread class class MultithreadingDemo extends Thread { public void run() { try { // Displaying the thread that is running System.out.println( "Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) { // Throwing an exception System.out.println("Exception is caught"); } } } // Main Class public class Multithread { public static void main(String[] args) { int n = 8; // Number of threads for (int i = 0; i < n; i++) { MultithreadingDemo object = new MultithreadingDemo(); object.start(); } } }
Runnable Interface Implementation for Thread Creation
In the new class, the run() method is overridden and executes the java.lang.Runnable interface. As a next step, we construct a Thread object and call its start() method.
// Java code for thread creation by implementing // the Runnable Interface class MultithreadingDemo implements Runnable { public void run() { try { // Displaying the thread that is running System.out.println( "Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) { // Throwing an exception System.out.println("Exception is caught"); } } } // Main Class class Multithread { public static void main(String[] args) { int n = 8; // Number of threads for (int i = 0; i < n; i++) { Thread object = new Thread(new MultithreadingDemo()); object.start(); } } }
Thread Syntax in Java
Extend Syntax:
public class Main extends Thread { public void run() { System.out.println("This code is running in a thread"); } }
Implement Syntax:
public class Main implements Runnable { public void run() { System.out.println("This code is running in a thread"); } }
Thread in Java Example
Example of Java Thread implementation of the Runnable interface
It is possible to create a class runnable by implementing the Java.lang.Runnable interface and supply its implementation in the public void run() method of that class. In order to run the run() method in a distinct thread, we need to construct a Thread object and pass the object of this runnable class as the argument. The following example implements the Runnable interface in Java.
package com.journaldev.threads; public class HeavyWorkRunnable implements Runnable { @Override public void run() { System.out.println("Doing heavy processing - START "+Thread.currentThread().getName()); try { Thread.sleep(1000); //Get database connection, delete unused data from DB doDBProcessing(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Doing heavy processing - END "+Thread.currentThread().getName()); } private void doDBProcessing() throws InterruptedException { Thread.sleep(5000); } }
Example of Extending the Thread Class in Java
It is possible to extend the Java.lang.Thread class in order to construct our own Java thread class overriding the run() method. After creating its object, we can execute its run method using the start() method of our custom Java thread class. Using the Thread class to extend a Java thread is shown in this simple example.
package com.journaldev.threads; public class MyThread extends Thread { public MyThread(String name) { super(name); } @Override public void run() { System.out.println("MyThread - START "+Thread.currentThread().getName()); try { Thread.sleep(1000); //Get database connection, delete unused data from DB doDBProcessing(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("MyThread - END "+Thread.currentThread().getName()); } private void doDBProcessing() throws InterruptedException { Thread.sleep(5000); } }
Thread Class Methods in Java
This class represents a variety of methods for operating threads as well. Some of them are:
setName() assigns a name to a thread
getName() returns the thread name
getPriority() returns a thread’s priority
isAlive() determines whether a thread is still active
join() waits for the thread to end
Run() initializes the thread
sleep() suspends a thread for a specified period of time
call start() to initiate a thread
activeCount() estimates the number of active threads in the thread group and subgroups of the current thread.
Which methods are Present in The Class Thread
There are several static methods provided by the Thread class, including:
- The currentThread() function returns the name of the thread that is currently executing. As this is a static method, we can reach the class name instantly.
public static Thread currentThread()
- sleep(): Sleeps the current thread for a limited amount of milliseconds. This technique halts the current thread in milliseconds for a specified amount of time.
public static void sleep(long milliseconds) throws InterruptedException
- yield(): By employing yield(), you can pause the current thread and authorize another thread that has the same preference to run. The thread currently executing gives up CPU control.
public static void yield()
- activeCount(): Returns the active thread count.
public static int activeCount()