Saturday, December 13, 2008

Simple Java Program to understand threading

/*
------------------------------------------------------------------------
Simple Java Program to understand threading
------------------------------------------------------------------------
*/
public class ThreadingExample{

private static class createdthread implements Runnable{

public void run(){
int i;
String threadname=Thread.currentThread().getName();//to get the name of current thread
System.out.format("%s is executing\n",threadname);
try{
for(i=0;i<4;i++){
Thread.sleep(1000);//pausing the thread for 1 second
System.out.format("%s",threadname+":"+i+"\n");
}
}catch(InterruptedException e){
System.out.format("%s is Interrupted\n",threadname);
}

}
}
public static void main(String args[]) throws InterruptedException{
int timeforexecutingt0;
timeforexecutingt0=Integer.parseInt(args[0]);
Thread t0 = new Thread(new createdthread());
Thread t1 = new Thread(new createdthread());
t0.start();//start executing thread 0
t1.start();//start executing thread 1
t0.join(timeforexecutingt0);//wait for thread 0 to finish within 'timeforexecutingt0'
t0.interrupt();//interrupt thread 0

}

}

/*
------------------------------------------------------------------------
Time for thread 0 will differ from one system to another. It may also differ based on the load on the system at the time of execution.Try finding whats the optimal time for your setup.
------------------------------------------------------------------------

C:\Users\flower\Documents\javaprogs>javac ThreadingExample.java

------------------------------------------------------------------------
Output when the execution time for thread 0 is not sufficient
------------------------------------------------------------------------
C:\Users\flower\Documents\javaprogs>java ThreadingExample 3000
Thread-0 is executing
Thread-1 is executing
Thread-1:0
Thread-0:0
Thread-1:1
Thread-0:1
Thread-0 is Interrupted
Thread-1:2
Thread-1:3

------------------------------------------------------------------------
Output when the execution time for thread 0 is sufficient
------------------------------------------------------------------------

C:\Users\flower\Documents\javaprogs>java ThreadingExample 5000
Thread-0 is executing
Thread-1 is executing
Thread-0:0
Thread-1:0
Thread-0:1
Thread-1:1
Thread-1:2
Thread-0:2
Thread-1:3
Thread-0:3

C:\Users\flower\Documents\javaprogs>*/

No comments: