Pageviews

Thursday 20 June 2013

Multi-threading in Java

by Unknown  |  in Threading at  Thursday, June 20, 2013

Multi-threading is a conceptual programming technique where a program is divided into smaller sub programs which can be implemented at the same time in parallel.It is basically used in programs where several parts work together,we can take example of Animation,using Multi-threading one sub-program can display an animation on the screen,while the other thread is built by the another sub program,so the lighter parts of the program are loaded first and heavier later.
Threading



What is a Thread ?:

 A Thread is a smaller part of a process that has single flow of control,it has a beginning,a body and an end.
  Java supports Multi-threading programming i.e Java enables us to use multiple flow of control in developing programs.Each flow of control may be thought of as a single separate program which is known as thread,so a program containing multiple flow of control is known as Multi-threaded program.

States of a Thread: Like a process,a thread also have states,these are as follows:


  • New Born State
  • Runnable State
  • Running State
  • Blocked State
  • Dead State 


1.New Born State: Whenever we create an object of thread,a thread is born and is said to be in new born state.

2.Runnable State: In this state,thread is ready  for execution,but it is waiting for the availability of the processor i.e. the thread has joined the queue of threads waiting for the execution.

3.Running State: The thread is provided the processor control,and is currently executing.

4. Blocked State: When a thread is suspended,sleeping or waiting ,then it is in Blocked state.

5.Dead State:When a thread is executed completely,then it goes to the Dead state.


So,here is the example of a simple program of Multi-threading in Java:

WAP to implement Multi-threading in Java:

class First extends Thread                                          //Thread is a in-built class in Java
{
public  void run()                                                       //in-built function-run()
{

for(int i=0;i<10;i++)
{
System.out.println("Value of i is");
}
}
}
class Second extends Thread
{
public void run()
{

for(int j=0;j<10;j++)
{
System.out.println("Value of j is");
}
}
}
class Third extends Thread
{
public void run()
{

for(int k=0;k<10;k++)
{
System.out.println("Value of k is");
}
}
}
class Test
{
public static void main(String arg[])
{
First Thread1=new First();
Second Thread2=new Second();
Third Thread3=new Third();
Thread1.start();                                                                   //Inbuilt function -start()
Thread2.start();
Thread3.start();
}
}


Threading



NOTE: The output of your program may go different because threading is based on scheduler and processor of your System.






0 comments:

Proudly Powered by Blogger.