Multithreaded programming in java
Multithreading is the concept of “doing many task at a time”.
In java, multithreading is mainly used in networking, where two or more nodes share the same resource and access it at a time.
There are two parts of a program that is in execution. They are: process and thread.
Thread is a lightweight process. They share the same address space. It has the separate part of execution.
There are several thread states, A thread can be in any one of the state at a particular point of time. It can be running state. It can be ready to run state as soon as it gets CPU time. A running thread can be suspended. A suspended thread can be resumed. A thread can be blocked when waiting for a resource. At any time a thread can be terminated.
The stages of thread 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: A runnable thread enters the terminated state when it completes its task or otherwise terminates.
Following is the list of important methods available in the Thread class.
|SN||Methods with Description|
|1||public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
|2||public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object.
|3||public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
|4||public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
|5||public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
|6||public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes.
|7||public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
|8||public final boolean isAlive()
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.