Friday, 26 July 2013

Multithreaded programming in Java

java  supports  multithreaded programming. A multithreaded program contains more than one part that can run parallerly. Each part  is called a thread, and each thread defines a separate way of execution.
The another term related to threads is process: A process consists of the memory space which is allocated by the operating system that can contain one or more threads. A thread must be a part of a process. A process remains running until all threads are done executing.
By Multithreading you can write  programs that make maximum use of the CPU, because idle time of CPU should be minimum.

Life Cycle of a Thread:

A thread goes through various stages in at time of execuition. The stages are shown below.
Java Thread
Stages  mentioned  above are explained here:
  • New: A new thread is created or born a It remains in this state until the program starts the thread.
  • Runnable: at this state the thread becomes runnable and thread considered to be executing its task.
  • Waiting: In this state the thread is waiting for the complition of task of another thread .
  • Timed waiting: A runnable thread can enter itn this stage for a short interval of time. 
  • Terminated: A runnable thread enters at this stage for to be terminated 

Thread Priorities:

Each Java thread has a priority order that which helps operating system to determine the order in which threads are to be execuited
  The range of priorities lies between MIN_PRIORITY (a constant of 1) and MAX_PRIORITY (a constant of 10). By default, every thread has priority NORM_PRIORITY (a constant of 5).
Threads has higer priority are more important tant.

Creating a Thread:

Java defines two ways :
  • By implement the Runnable interface.
  • B extend the Thread class, itself.

Create Thread by Implementing Runnable:

The first  way is to create a class that implements the Runnable interface.
 A class need only implement a single method called run( ), which is declared like this:
public void run( )
Inside run( ), you may define the code that of  new thread. It is
important to understand that run can call other methods,  other classes, and
declare variables, 


Create thread by extend the Thread class : 

for  creation  of a athread is to  extends Thread class,
and then to create an object  of that class. The  class must override the
run( ) method of thread class, in which u can define the new thread. It must also call start( ) method 
to begin execution of the new thread. 

0 comments:

Post a Comment