Core java tutorial for beginners
A tutorial blog which explains different core concepts related to Java along with programming examples
Subscribe to Startertutorials.com's YouTube channel for different tutorial and lecture videos.

Categories: Multithreading. 3 Comments on Mutlithreading in Java

In this article we will learn what is multithreading and how to create and use threads in Java programs.

 

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:

  1. Extend the Thread class or
  2. Implement the Runnable interface

 

The Thread class contains the following methods:

 

multithreading-thread-class

 

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:

  1. It is used to create child threads.
  2. 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.

How useful was this post?

Click on a star to rate it!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Suryateja Pericherla

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.

Note: Do you have a question on this article or have a suggestion to make this article better? You can ask or suggest us by filling in the below form. After commenting, your comment will be held for moderation and will be published in 24-48 hrs.

3 Comments

You can follow any responses to this entry through the RSS 2.0 feed.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *