Wednesday, 29 August 2012

Program for calculating total elapsed time using the concept of multithreading and System.currentTimeMillis() method.


import  java.io.*;
class Child extends Thread
{
Child(String str)
{
super(str);
start();
}
public void run()
{

try
{
for(int n=1;n<=5;n++)
{
System.out.println("Child thread: "+n);
Thread.sleep(1000);
}

}
catch (InterruptedException e)
{
System.out.println("Child interrupted.");
}

}
}

class prog
{
public static void main(String a[]) throws Exception
{
long timestart = System.currentTimeMillis();
new Child("child");

Thread t = Thread.currentThread();
//System.out.println("current thread"+t);
t.setName("my thread");

try
{

for(int n=1;n<=5;n++)
{
System.out.println("main thread: "+n);
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println("not  valid");
}
long timelast = System.currentTimeMillis();
float result =(timelast-timestart)/1000;
System.out.println("total time elapsed in seconds :  "+result);

}
}


main thread: 1
Child thread: 1
main thread: 2
Child thread: 2
main thread: 3
Child thread: 3
Child thread: 4
main thread: 4
main thread: 5
Child thread: 5
total time elapsed in seconds :  5.0