
A multithreading in Java is a concept where we split a program into two or more sub-programs and execute them at the same time.
If we take real world example, we can assume that there is a task which we divide into sub tasks and assign them to different people for execution independently and simultaneously. The main objective of multitasking is to improve the performance of the system by reducing the response time.
Before going into the details of multithreading, let’s get an idea about threads.
Table of Contents
What is Thread in Java?
When more than one task is executed simultaneously, where each task is a separate independent part of the same program, that independent part of the program is called a Thread.
It is light-weight because it uses minimum resources of the system, it means thread takes less memory and less processor time.
Ways to define thread in Java
There are mainly two ways to define thread which are as follows:
- By extending Thread class.
- By implementing Runnable interface.
Defining a thread by extending Thread class
In this way we extends a Thread class and override the run() method. In this method of thread creation, you need not to create Thread class object implicitly because when you create an object of child class the Thread class constructor will also invoked.
Steps of creating Thread and running it
- Create a class that extends Thread class.
- Override the run() method.
- Create an object to the created class.
- Use start() method to run the thread.
public class ThreadDemo extends Thread {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Child Thread");
}
}
public static void main(String[] args) {
ThreadDemo obj = new ThreadDemo();
obj.start();
for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread");
}
}
}
Output: Child Thread Child Thread Main Thread Child Thread Main Thread Main Thread Child Thread Main Thread Main Thread Child Thread
start() Vs run() method Multithreading in java
If you call the start() method then new thread will be created and that thread executes the run() method.
If you call the run() method directly then no new thread will be created and run() method will execute just like a normal method.
Defining a thread by implementing Runnable interface
You can define thread by implementing Runnable interface which is present in java.lang package and it only contains run() method.
Steps of creating thread by using Runnable interface
- Declare a class and implement Runnable interface.
- Override the run() method.
- Create an object of created class.
- Create an object of Thread class and pass the object of created class into the constructor of Thread class.
- Call start() method.
public class ThreadDemo implements Runnable {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
System.out.println("Child Thread");
}
}
public static void main(String[] args) {
ThreadDemo obj = new ThreadDemo();
Thread t = new Thread(obj);
t.start();
for (int i = 1; i <= 5; i++) {
System.out.println("Main Thread");
}
}
}
Output: Main Thread Child Thread Child Thread Main Thread Child Thread Main Thread Main Thread Child Thread Child Thread Main Thread
Life Cycle of Thread in Java
There are 5 states in Java Thread. A thread is always in one of these five states. It can move from one state to another.
- New: When new Thread object is created.
- Ready/Runnable: When start() method of Thread class is invoked.
- Running: If thread scheduler allocates the CPU.
- Waiting/Non-Runnable/Blocked: When the thread is still alive, but is currently not eligible to run.
- Terminated: If run() method completes then it enters into the terminated state.
When you create a Thread class object, a thread will born. Then, when you call the start() method, the thread goes into runnable state. It is possible that yield() method may pause a thread, but the tread will be still in runnable state. When sleep() or wait() methods act on thread, a thread may get into non-runnable state. if user provides required input/output, the thread comes out from the non-runnable state, and it comes back into the runnable state. When a thread comes out of run() method, a thread is terminated from memory.
All these state transitions of a thread are called “thread life cycle”.
sleep Vs wait method in java
There are following differences between sleep and wait method in java.
# | sleep() method | wait() method |
1 | Thread class includes the sleep method. | The wait function belongs to the Object class. |
2 | The sleep method is a static method. | The wait method is a instance method. |
3 | When the timer ends, the sleep() function will be immediately woken up. | Another thread can wake up a wait() by invoking notify() or notifyAll(). |
4 | Before entering the waiting state, this method does not release the lock. | This method will release the lock before going to waiting state. |
5 | This method does not require a synchronized block to be called. | Only synchronized context (method or block) will call this method. |
Thread Schedular
The thread scheduler decides which thread should run. In other words, the thread scheduler decides which thread will get the first chance if multiple threads wait for a chance to execute. It is the part of JVM and the behavior of the thread scheduler is vendor specific.
In case of multithreading in java we can tell the possible output but not the exact output.
Thread Priority
Thread priority affects the order in which the thread scheduler allocates CPU. The highest priority thread will get the chance first and the lowest priority thread will get the chance last.
If multiple threads have same priority then you cannot expect execution order, it will depend on thread scheduler.
Default priority of a thread is 5. The value of minimum priority of a thread is 1 and maximum priority of a thread is 10.
Thread class defines the following constants for the thread priority
- Thread.MIN_PRIORITY – 1
- Thread.MAX_PRIORITY – 10
- Thread.NORM_PRIORITY – 5
Thread scheduler uses these priority to allocate the CPU.
Thread class defines the following two methods to get and set the priority of a thread.
public final int getPriority(); public final void setPriority(int priority);
As you know you can put the number from 1 to 10, if you put other than these values then you will get IllegalArgumentException.
Prevent Thread execution
There are following methods by which you can prevent thread execution
- yield()
- join()
- sleep()
Let’s discuss about these three method which prevent java thread execution in multithreading as well.
yield() method
The yield() method pauses the current executing thread to give a chance to other remaining waiting threads of the same priority.
If there is no waiting thread or all the waiting threads have a lower priority then the same thread will once again continue its execution.
public static native void yield();
join() method
If a thread wants to wait till the completion of another thread then we should use join() method.
If there are two threads, t1 and t2, if t1 executes t2.join(), then t1 will enter into the waiting state until t2 completes. Once t2 completes then t1 will continue its execution.
public void join()throws InterruptedException public void join(long milliseconds)throws InterruptedException public void join(long milliseconds, int nanoseconds)throws InterruptedException
sleep() method
If a thread do not want to perform any operation for some time then we should use sleep() method. It pauses the thread execution for a particular amount of time.
public static void sleep(long milliseconds)throws InterruptedException public static void sleep(long milliseconds, int nanoseconds)throws InterruptedException
Thread Interruption in Java
In the multithreading environment, a thread can interrupt another waiting or sleeping thread
public void interrupt();
If you call the interrupt() method, you may not see the effect immediately. Whenever you call the interrupt() method, if the target thread is not in the waiting or sleeping state, the interrupt call will wait until the target thread enters the sleeping or waiting state. The interrupt call will take effect on the target thread once the target thread enters the sleeping or waiting state.
In conclusion, by going through this article hope you got an idea of threading , multithreading in java and how to create a thread by using Thread class and Runnable interface.