Wednesday, 5 September 2012

Java Thread


Introduction of Java Thread


A thread is a program's path of execution. In other words, a thread is a single sequential flow of control within a program. 
A thread, by definition is a light weight process. They are used to increase functionality and performance by performing multiple tasks at the same time, i.e. concurrently. There are two methods for implementing threads in Java,
  • Extending Thread class
  • Implementing Runnable interface
 By Extending Thread class
 
 Save Job.java
 
 class Job extends Thread
{
 private int start;
 private int stop;
 private String name;
 
 Job(String name, int start, int stop)
 {
  this.name = name;
  this.start = start;
  this.stop = stop;
 }
 
 public void run()
 {
  performJob();
 }
 
 public void doJob()
 {
  start();
 }
 
 private void performJob()
 {
  System.out.println(name + " started...");
  int i;
  for (i=start;i<=stop;i++)
  {
   System.out.println(name + " : " + i);
  }
  System.out.println(name + " terminated...");
 }
}

Save MT1.java

public class MT1
{
 public static void main(String args[])
 {
  System.out.println("Main Thread Started...");
  Job j1, j2, j3;
  j1 = new Job("Job1",1,30);
  j2 = new Job("Job2",60,90);
  j3 = new Job("Job3",180,210);
  j1.doJob();
  j2.doJob();
  j3.doJob();
    }
}

By implementing Runnable interface

Save Job.java
 
 class Job implements Runnable
{
private int start;
 private int stop;
 private String name;
 Thread t;
 
 Job(String name, int start, int stop)
 {
  this.name = name;
  this.start = start;
  this.stop = stop;
  t = new Thread(this);
 }
 
 public void performJob()
 {
  t.start();
 }
 
 public void run()
 {
  doJob();
 }
 
 private void doJob()
 {
  System.out.println(name + " started...");
  for (int i=start; i<=stop; i++)
   System.out.println(name + " : " + i);
  System.out.println(name + " terminated...");   
 }
}

Save MT1.java

public class MT1
{
 public static void main(String args[])
 {
  System.out.println("Main Thread Started...");
  Job j1, j2, j3;
  j1 = new Job("Job1",1,30);
  j2 = new Job("Job2",60,90);
  j3 = new Job("Job3",180,210);
  j1.doJob();
  j2.doJob();
  j3.doJob();
    }
}

1 comment:

  1. Sugarboo extra long digital titanium styler
    Sugarboo extra long digital titanium styler. $25.40. 출장마사지 Regular price $0.25. Quantity: titanium network surf freely Add to cart. titanium prices Description. The sugarboo extra titanium glasses long digital titanium metal babyliss pro nano titanium curling iron styler

    ReplyDelete