A thread is the sequential programs described previously. A single thread also has a beginning, a sequence, and an end. At any given time during the runtime of the thread, there is a single point of execution.
However, a thread itself is not a program; a thread cannot run on its own. Rather, it runs within a program.
The following figure shows this relationship.
A thread is an independent path of execution within a program. Many threads can run concurrently within a program. Every thread in java is created and controlled by the java.lang.
Single Thread
In a single thread or threading, the process contains only one thread. That thread executes all the tasks related to the process. It executes a process in single threading
Multi thread
In a multi-threaded application, multiple threads are executed concurrently. Each thread handles different tasks simultaneously by making optimal use of the resources. In Java, there are two methods to create threads. These are by implementing a Runnable interface or extending the Thread class.
Thread life Cycle
Ready
A thread is in Ready state after calling start(). In this state, a thread is ready for execution.
Running
In this state, CPU is allocated to thread and thread is in execution.
Sleeping
In this state, a thread is in sleeping mode for a specific time after calling sleep(). It will resume automatically when the time specified expires.
Suspended
In this state, thread is temporarily suspended after calling suspend(). It will be resume after calling resume() method.
Dead
In this state, a thread is killed after the completion of its execution.
Creating a Thread
There are two ways to create a thread.
It can be created by extending the Thread class and overriding its run() method:
Extend Syntax
public class Main extends Thread {
public void run() {
System.out.println("This code is running in a thread");
}
}
Another way to create a thread is to implement the Runnable interface:
Implement Syntax
public class Main implements Runnable {
public void run() {
System.out.println("This code is running in a thread");
}
}
The Tech Platform
コメント