Multithreading in java is running multiple threads sharing same address space concurrently. A multithreaded program has two or more parts running simultaneously. Each part is called a thread and has a separate path of execution. Multithreading allows a process to run its tasks in parallel mode and execute these different tasks simultaneously.
Multithreading in java is running multiple threads sharing same address space concurrently. A multithreaded program has two or more parts running simultaneously. Each part is called a thread and has a separate path of execution.
A thread is run inside a process, which consists of the memory space allocated by the operating system. A thread never exists on its own. Multithreading allows various threads to run inside one process.
Carrying out more than one task at a time is called Multitasking. (A CPU does multitasking all the time). Now, multitasking can be carried out in two ways:
- Multiprocessing
- Multithreading
Multithreading allows a process to run its tasks in parallel mode and execute these different tasks simultaneously.
Following are 4 states of Thread:
- New: Here the thread object has been created but it has not been initialized
- Ready-to-Run: The thread object is ready-to-run whenever the CPU gives it a time slot.
- Running: CPU has allotted the time slot and thread is running
- Dead (Terminated): The thread has been terminated
A running thread can further enter into non-runnable states, which are:
- Sleeping: In this state a thread sleeps for a specified amount of time.
- Blocked for Join Completion: A thread enters into this non-runnable state because of waiting the completion of another thread.
- Blocked for I/O: The thread waits for completion of blocking operation.
- Waiting for notification: Till the thread waits for notification from another thread it is in this non-runnable state. However, once it gets the notification it comes back to Ready-to-Run state.
- Blocked for lock acquisition: A thread enters into this non-runnable state because of waiting to acquire the lock of an object.
In Java, lifecycle of thread is controlled by Java Virtual Machine (JVM). It allows a program to be more responsible to the user. When a program contains multiple threads then the CPU can switch between the two threads to execute them at the same time.
Following is an example of Multithreading:
public class multi extends Thread { @Override public void run() { System.out.println(); for (int x = 1; x <= 3; x++) { System.out.println(x + " Thread name" + Thread.currentThread().getName()); } } public static void main(String[] args) { multi t1 = new multi(); t1.start(); multi t2 = new multi(); t2.start(); multi t3 = new multi(); t3.start(); } }