About Me

header ads

MULTI-THREADING in JAVA

MULTI THREADING 



Definition

Multi threading is a technique that allows a program or a process to execute many tasks concurrently ( at the same time and parallel ). It allows a process to run its tasks in parallel mode on a single processor system.

In the multi threading concept , several multiple lightweight processes are run in a single process/task or program by a single processor.

In java , the java virtual machine (JVM) allows an application to have multiple threads of execution running concurrently.

Example

In this diagram , two threads are being executed having more then one task. The task of each thread is switched to the task of another thread
Life cycle of a thread
A thread goes through various stages in its life cycle. For example , a thread is born , started , runs and then dies . Following diagram shows complete life cycle of a thread.
1-: New

2-: Runnable

3-: Waiting

4-: Timed waiting

5-:Terminated

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 become runnable . A thread in this stage is considered to be executing its task.
Waiting
Some times a thread transitions to the waiting state while the threads 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 the timed waiting state for a specified interval of time . A thread in this state transitions back to the runnable state when that interval time 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 it terminate.

Creating a thread 
Java defines the two way in which this can be accomplished.
You can implement the Runnable interface.
You can extend the thread class itself.

Implementing Runnable

To implement Runnable , a class need only implement a single method called Run() . Which is declared like this.
public void run()

Extend the thread 

The second way to create a thread is to create a new class that extends thread , and then to create an instance of the class.
The extending class must override the Run() method . Which is the entry point for the new thread . It must also call start() to begin execution of the new thread.

Methods with description 

1-: public void start()

Starts the thread in 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 void interrupt()

Interrupts this thread , causing it to continue execution if it was blocked for any reason.