A thread is a section of code executed independently with in a program.
Multithreading is an execution of the multitasking paradigm, where instead multiple program, multithreading involves multiple thread within a single program.
A main() method in the java program creates the main thread. When a java application begins, the java virtual machine creates a java thread referred to as the main thread for you program.
The different types of creating thread in a java program is, Implementing Runnable Interface, extending Thread class.
Create thread with Runnable Class:
The simplest way to create a thread is to create a class that implements the runnable interface. The runnable interface is a simple interface, with only one method run(). The class that implements the runnable interface should define the run() method to create a thread.
Create a thread using Thread Class:
To create a thread, create a new class that extends the Thread clas, and override the run() method in the sub class. A new thread is born when we create an instance of the Thread class, which represents a real thread in the java interpreter.
To start a thread, all you need to do is to call the start () method of the thread class. Which gives life to a newly created class.
To find a thread is running or not:
To check a thread, whether it is running ot not, all you need to is to call isAlive() method of the thread class. If the isAlive() method returns true, it means that the thread is still running and returns false of not running,
To pause a thread use sleep() method. The time specified in milliseconds as an argument to the method.
To destroy a thread, all you need to do is call stop () method.
The general task of managing and executing multiple threads in an environment such as this is known as thread scheduling.
When does thread stops its execution:
1. The run() method completes its execution.
2. The thread is interrupted by an uncaught exception.
3. The stop() method completes its execution.
A preemptive scheduler, is a thread scheduler preempts (pause) a running thread to allow different threads to execute.
A non-preemptive scheduler never interrupts a running thread, instead, the non-preemptive scheduler relies on the running thread to get control of the CPU so that other threads may execute.
When does starvation and deadlock occurs in a thread:
Starvation occurs when a thread is completely cut from the resources and can’t make any progress. The thread is effectively frozen, Starvation can apply to a number of threads individually. Deadlock occurs when two or more threads are waiting for a mutual condition that can never be satisfied (i.e they are starving each other).