Multi Thread programming
Any application can have multiple processes (instances). Each of this process can be assigned either as a single thread or multiple threads.
What is Single Thread?
A single thread is basically a lightweight and the smallest unit of processing. Java uses threads by using a "Thread Class".
There are two types of thread – user thread and daemon thread (daemon threads are used when we want to clean the application and are used in the background).
When an application first begins, user thread is created. Post that, we can create many user threads and daemon threads.
1 package demotest;
2public class GuruThread
3{
4 public static void main(String[] args) {
5 System.out.println("Single Thread");
6 }
7}
What is Multithreading in Java?
MULTITHREADING in Java is a process of executing two or more threads simultaneously to maximum utilization of CPU. Multithreaded applications execute two or more threads run concurrently. Hence, it is also known as Concurrency in Java. Each thread runs parallel to each other. Mulitple threads don't allocate separate memory area, hence they save memory. Also, context switching between threads takes less time.
1 package demotest;
2public class GuruThread1 implements Runnable
3{
4 public static void main(String[] args) {
5 Thread guruThread1 = new Thread("Guru1");
6 Thread guruThread2 = new Thread("Guru2");
7 guruThread1.start();
8 guruThread2.start();
9 System.out.println("Thread names are following:");
10 System.out.println(guruThread1.getName());
11 System.out.println(guruThread2.getName());
12 }
13 @Override
14 public void run() {
15 }
16}
Advantages of multithread:
- The users are not blocked because threads are independent, and we can perform multiple operations at times
- As such the threads are independent, the other threads won't get affected if one thread meets an exception.
Following are the stages of the life cycle −
- New − A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.
- Runnable − After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.
- Waiting − Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.
- Timed Waiting − A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.
- Terminated (Dead) − A runnable thread enters the terminated state when it completes its task or otherwise terminates.
0 Comments