Multithreaded programs can be developed using the Java Programming language. By a multithread program, it means a program comprises of two or more actions, where each action performs different tasks simultaneously. Multithreading can also be said as a synonym for multitasking where each thread corresponds to each task. The benefits of multithreaded program are that multiple activities run parallel and use the same program.
What is a Thread?
A thread in a Java program in its simplest definition is a sequential flow of statements that defines an execution path for a program. A Java program should contain at least one thread that is the main thread, which is invoked by the main () method.
Ways to Create a Java Thread
The Thread class is one of the main classes in Java that is written as java.lang.Thread class. This class, along with the Runnable interface, is used to create threads in Java. A thread in Java can be created in either of the two following ways:
- Extending the java.lang.Thread class
- Implementing the java.lang.Runnable Interface
Life Cycle of a Java Thread
A thread in a Java program goes through different states, as shown in the following flowchart:
A brief description of these states is as follows:
- New: Refers to the state after an instance of the Thread class gets created but before the invocation of the start () method. This state marks the beginning of life cycle of a thread.
- Runnable: Refers to the state where a thread executes the task for which it is created. The thread comes into this state after the start() method is invoked.
- Running: Refers to the state where thread is selected by the scheduler for the execution purpose.
- Not-Runnable (Blocked): Refers to the state where thread is alive; however it is not eligible to run.
- Terminated: Refers to the state when a thread gets terminate and is in a dead state.
Familiarizing with Thread Priorities
We are aware of the availability of multiple Java threads in a program. But the question that arises is how a program knows which thread to run first or sequence of execution order for all threads. The solution to this can be given by scheduling thread execution. Each thread in a Java program has a priority. By default, priority of a thread is inherited by its parent thread and is in between numbers 1 to 10, where number 1 denotes that thread is at the minimum priority level and 10 denotes the highest priority level for a thread. Further, thread priority can also be changed according to the requirement using the java.lang.Thread.setPriority () method.