Java Multithreading

Java Multithreading is a lightweight process. In this post will understand Threading in java concepts in which many people find tricky to use and understand. I hope at the end of this post readers should be able to write simple programs using threads.

What are threading in java ?

A thread is a lightweight process and defines a separate path for execution.

* All Java programs have at least one thread, known as the main thread, it is created by the Java Virtual Machine (JVM) when program’s start i.e when the main() method is invoked with the main thread.

* Thread is a smallest unit of processing and independent in nature.

* The failure of one thread does not affect other threads. It shares a common memory area , as shown in the below diagram.

Java threading

From the above diagram we can say that, thread is executed inside the process and it has context-switching between the threads. There can be multiple processes inside the OS and one process can have multiple threads.

Note: At a time only one thread can executed.

General Overview of threads

A threading in java has independent path of execution within a java program. Many threads can run concurrently within a program. Every thread in Java is created and controlled by the java.lang.Thread class.

* Java is a multi-threaded application support multiple thread execution at any particular time.

* In a single-threaded application, only one thread is executed at a time i.e program can handle only one task at a time.

Example

Application can perform single task i.e typing of words.

* In a multi-threaded application, more then one thread can executed at a time.

Example

Application can perform recording and typing the keystrokes within one application.

* When a thread is created, it is assigned a priority. The thread with higher priority is executed first, followed by lower-priority threads.

Advantages of Multi-threading in Java

1. It support multiple operations at a time.

2. It save lot of time due to multiple operations at a time.

3. Independent in nature thus making the functionality better.

Uses of Threads in Java

* Threads to make Java application faster by doing multiple task at a time.

* Thread in Java mainly used to perform multiple tasks simultaneously.

For example, in GUI applications i.e draw screens at the same time capture user’s action.

* Take advantage of multiprocessor systems in large data centers.

* Threads in java make our programs simpler to write and maintain.

* It is mainly used to perform asynchronous or background processing.

Types of Threads

There are two types of Threads in java.

  1. User Thread
  2. Daemon thread

User Thread

* User Thread are created by the application or user.

* It is a high priority threads in java. For example, JVM (Java Virtual Machine) will not exit until all user threads finish their execution, wait for these threads to finish their task.

* It is a foreground threads.

Daemon Thread

* Daemon threads are threads are created by the JVM.

* It is a less priority threads in java. For example, JVM does not wait for daemon threads to finish their task.

* It run in the background, perform some of the task like garbage collection and house-keeping tasks.

Life Cycle of Thread

The life cycle of the thread in java as the following states like,

  1. New
  2. Runnable
  3. Running
  4. Blocked or Waiting
  5. Dead

* The life cycle of the thread in java is controlled by JVM.

life cycle of thread

Let’s study one by one.

New

When we create an instance of Thread class, then thread is in a new state. But not yet started the execution i.e before the invocation of start() method.

Runnable

When the thread is in runnable state after calling of start() method i.e The Java thread is in running state,but the thread scheduler has not selected.

Running

The thread is in running state when the thread scheduler has selected.

Waiting or Blocked

The thread is in alive state, but currently it is not eligible to run.

Dead

The thread is in dead state when it is completed its execution.

Thread Priority

Thread priority is defined as how thread should be treated with respect to other thread.

In java every thread has priority which is defined by a number between 1 to 10. The threads with higher priority will run first than lower priority threads.

* Thread priority is listed in the below table.

MAX_PRIORITY10
NORM_PRIORITY5
MIN_PRIORITY1

Note:  A default priority for a thread is 5 

* In java thread scheduler schedules the threads according to their priority is known as preemptive scheduling.

* In thread we can get and set the priority of thread using “Thread.getPriority()” method and “Thread.setPriority()” method.

Coding

class demo extends Thread{

public void run(){

System.out.println(“running thread name is:”+Thread.currentThread().getName());

System.out.println(“running thread priority is:”+Thread.currentThread().getPriority());

}

public static void main(String args[]){

demo m1=new demo();

demo m2=new demo();

m1.setPriority(Thread.MIN_PRIORITY);

m2.setPriority(Thread.MAX_PRIORITY);

m1.start();

m2.start();

}

}

Screenshot

Thread priority

How to Implement thread in java ?

In java we can implement thread in two ways,

  1. By implementing the Runnable interface.
  2. By extending the Thread

Runnable Interface

It is the easiest and recommended way to implement a thread in java, in this method we can extends any other class and we are getting the benefits of Inheritance.

Benefits

* Here we can can save a lot of space for class to extend any other class in future or present.

* It shares the same object to multiple threads.

Coding
 package sample2;

//Java program to defining Thread

//by implements Runnable interface

 

public class demo2 {

public static void m1()

{

System.out.println(“Hello beyondcorner readers”);

}

}

//Here we can extends any other class

class Test extends demo2 implements Runnable {

public void run()

{

System.out.println(“Run method executed by child Thread”);

}

 

public static void main(String[] args) {

Test t = new Test();

t.m1();

Thread t1 = new Thread(t);

t1.start();

System.out.println(“Main method executed by main thread”);

 

}

 

}

Screenshot

Runnable Interface

Extending Java Thread

It is a another way to implement thread in java, here class always extends Thread class. There is no chance of extending any other class. Hence we are missing  the benefits of Inheritance.

Limitations

* If we extend Thread class, we can not extend any other class even it is required.

* If we extend Thread class, each thread creates unique object and associate with it.

Coding

public class Test extends Thread  {

public void run()

{

System.out.println(“Run method executed by child Thread”);

}

public static void main(String[] args) {

Test t = new Test();

t.start();

System.out.println(“Main method executed by main thread”);

}

}

Screenshot

Extending Java Thread

Note: Interface approach is recommended in java than extending Thread class.

What is thread class in Java ?

Thread class is the main class in java and multithreading system is completely depends on the thread class.

* Thread class along with interface Runnable are mainly used to create and run threads by utilizing Multithreading feature of Java.

* It defines few methods, which are used to manage behavior of threads which are listed below.

MethodMeaning
getNamereturn thread’s name
getPriorityreturn thread’s priority
isAlivechecks if thread is still running or not
joinWait for a thread to end
runEntry point for a thread
sleepsuspend thread for a specified time
startstart a thread by calling run() method

“That’s all about the Threading in java, i hope readers find useful”

 

 

 

 

 

 

Leave a Reply

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