Multithreading in Java

Multithreading in Java

Multithreading, another feature of OOPs, in common words Multithreading in Java helps to execute more than 2 programs simultaneously and we can utilize the capacity of CPU. 

1. How Java Thread work

A thread is just a single lightweight process. It is the smallest unit of processing. Applications can have multiple processes. Each of the processes is assigned to a single thread or multiple threads.

When these threads work concurrently then this procedure is known as multithreading.

A multi-threaded program contains multiple parts that can run simultaneously. Each part of the process is a thread and every thread defines a separate part of the execution.

2. How Multithreading works in Java?

Multithreading in Java is a process of executing two or more threads simultaneously. To achieve multitasking we use multiprocessing and multithreading. Each thread runs parallel to each other.

Although, we use multithreading because the threads use a shared memory area. They don’t allocate separate memory area so it saves the memory. Also, context switching between threads takes less time. Multithreading is mainly used in gaming.

3. Life Cycle of a Thread in Java

A thread in multithreading in Java has a predefined lifecycle which it goes under. Following are the various stages under which it goes –

New – As soon as, you create new thread, it’s in NEW state. It remains in this state until the program starts the thread using it’s start() method.

At this point, thread is not alive and it’s a state internal to Java programming.

Runnable – Calling start() method on thread put it in RUNNABLE state. At this point, execution control is passed to thread scheduler to finish it’s execution. Thread scheduler decide from this point that this thread should be executed (also known as dispatching the thread) or should be put on hold to give chance to other runnable threads.

The process that an operating system uses to determine which thread to dispatch is called thread scheduling and is dependent on thread priorities.

Waiting – A thread can be put in waiting state for various reasons e.g. calling it’s wait() method. Usually program put a thread in WAIT state because something else needs to be done prior to what current thread is doing.Once the thread wait state is over or it is, it’s state is changed to RUNNABLE and it’s moved back to thread pool.

Timed waiting –

A RUNNABLE thread can transition to the TIMED WAITING state if it provides an optional wait interval when it’s waiting for another thread to perform a task. You can put a java thread in TIMED WAITING state by calling it’s sleep(long millis) method or wait(long millis) method.

Such a thread returns to the RUNNABLE state when it’s notified by another thread or when the timed interval expires—whichever comes first.

Timed waiting threads and waiting threads cannot use a processor, even if one is available.

Terminated (dead ) – A thread enters the TERMINATED state (sometimes called the dead state) when it successfully completes its task or otherwise terminated due to any error or even it was forcefully killed.

Java Thread Life Cycle States
Java Thread Life Cycle States

4. Advantages of Multithreading in Java

  • It allows performing multiple operations at once, as they are not dependent on each other, thus not blocking the user.
  • It saves time as multiple operations are possible.
  • They are independent to make the functionality better.

5. How to Achieve Multithreading in Java?

There are two ways to achieve multithreading in Java-

  • By Implementing the Runnable Interface
  • By extending Thread class

5.1 Implementing the Runnable Interface in Java

The simplest way to create a thread is to create a class by implementing the Runnable interface. To do this we need a class which implements a single method called run( ), which is declared like this

class MultithreadingDemo implements Runnable {
public void run() {
try {
System.out.println("Thread " + Thread.currentThread().getId() + " is running");
} catch (Exception e) {
System.out.println("Exception is caught");
}
}
}
public class MainClass {
public static void main(String args[]) {
for (int count = 0; count < 8; count++) {
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}

5.2 By extending Thread class

Another way to create a thread is by creating a new class that extends the Thread, then it overrides the run() method and then it creates an instance of that class. The run() method is executed when you call start() method. Here is an example of creating a Java Thread subclass:

class MultithreadingDemo1 extends Thread {
public void run() {
try {
System.out.println("Thread " + Thread.currentThread().getId() + " is running");
} catch (Exception e) {
System.out.println("Exception is caught");
}
}
}
public class MainClass {
public static void main(String[] args) {
for (int count = 0; count < 8; count++) {
MultithreadingDemo1 object = new MultithreadingDemo1();
object.start();
}
}
}

Reference:

%d bloggers like this: