In this article we will learn what is multithreading and how to create and use threads in Java programs.
Contents
Background Information
Multitasking: Ability to execute two or more tasks in parallel or simultaneously is known as multitasking. Multitasking is of two types: 1) Process based multitasking and 2) Thread based multitasking.
Process based multitasking: Executing two or more processes simultaneously is known as process based multitasking. For example, we can listen to music and browse internet at the same time. The processes in this example are the music player and browser.
Thread based multitasking: Thread is a part of process i.e., a process can contain one or more threads. If two or more such threads execute simultaneously, it is known as thread based multitasking or multithreading.
For example, using a browser we can navigate through the webpage and at the same time download a file. In this example, navigation is one thread and downloading is another thread.
Another example for multithreading is in a word-processing application like MS Word, we can type text in one thread and spell checker checks for mistakes in another thread.
Java doesn’t provide control over process based multitasking. But, it allows programmers to control multithreading.
Advantage of multithreading is, it increases CPU utilization i.e., CPU is made busy (always executing some thread) without leaving it idle.
Multithreading in Java
A thread is a separate flow of execution in a program. All Java programs by default contain a single thread called the “Main thread”. A thread contains a set of statements like a method in Java.
The difference between thread and a method is, unlike methods, threads can run simultaneously or in parallel with other threads.
On a machine with single CPU threads cannot run in parallel exactly. Only one thread can run at a time. This kind of concurrency is called quasi-concurrency. But, on a machine with multiple cores or multiple CPUs, each CPU can run a single thread in parallel.
The Thread class and the Runnable Interface
Threads in Java are supported through Thread class and Runnable interface. A single thread is represented in a Java program as Thread class instance (object). To create a new thread in a Java program, we can either:
- Extend the Thread class or
- Implement the Runnable interface
The Thread class contains the following methods:
Main Thread
When a Java program is executed, by default it starts a single thread of execution. That thread is known as the “Main thread”. The main thread is important due to two reasons:
- It is used to create child threads.
- It is the last thread to terminate during which it will perform various shutdown operations.
We can control the main thread by obtaining a reference to it using the Thread object as shown in the below program:
public class Driver
{
public static void main(String[] args)
{
Thread mainThread = Thread.currentThread();
System.out.println("Current thread: " + mainThread);
mainThread.setName("My Thread");
System.out.println("After name change: " + mainThread);
try
{
for(int i = 1; i <= 5; i++)
{
System.out.println("i = " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Thread is interrupted!");
}
}
}
In the above program main thread reference is obtained by using the currentThread() method in Thread class. The setName() method is used to assign a new name to the main thread. The new name assigned to the main thread is My Thread.
The sleep() method is used to pause the current thread (main thread) for certain amount of time which is specified in milliseconds. In the above program 1000 in the sleep() method pauses the thread for 1 second.
Output of the above program is:
Current thread: Thread[main,5,main]
After name change: Thread[My Thread,5,main]
i = 1
i = 2
i = 3
i = 4
i = 5
In the above output, [main,5,main], first main refers to the name of the thread, 5 refers to the default priority of the main thread and last refers to the thread group name which is also main.
Syntax of some the methods used above are as follows:
static Thread currentThread()
static void sleep(long milliseconds) throws InterruptedException
final void setName(String threadName)
final String getName()
In the next article we will learn how to create new threads using Thread class and Runnable interface.
Suryateja Pericherla, at present is a Research Scholar (full-time Ph.D.) in the Dept. of Computer Science & Systems Engineering at Andhra University, Visakhapatnam. Previously worked as an Associate Professor in the Dept. of CSE at Vishnu Institute of Technology, India.
He has 11+ years of teaching experience and is an individual researcher whose research interests are Cloud Computing, Internet of Things, Computer Security, Network Security and Blockchain.
He is a member of professional societies like IEEE, ACM, CSI and ISCA. He published several research papers which are indexed by SCIE, WoS, Scopus, Springer and others.
Thanks for sharing this information
hey thanks for this great information on multi threading in java. I have found this really helpful. Here you covered all the things regarding multi-threading. keep up the great work.
Your work is amazing sir, handsoff to you my kindely request to present r16 jntuk curriculum for our cse. And start research groups and help students in research side. Great job sir.