Friday, August 21, 2009

Java : Simple Thread Example

How to start new thread from main thread. Any program starts execution from main thread how ever you can start n numbers of threads from this main thread. Lets see a simple Thread example, just compile and run main program and see output.

/* MainClass.java */

public class MainClass
{
public static void main(String[] args)
{

System.out.println("Main Thread Started");

AnotherClass ac = new AnotherClass();
//Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
ac.start();

for(int i=0;i<=10 ;i++ )
{
System.out.println("Main "+i);

try
{
//Get current Thread
Thread.currentThread().sleep(300);
}
catch (InterruptedException ex)
{
//sleep() method throws this checked exception
System.out.println("Exception in MainClass thread : "+ex);
}

}
System.out.println("Ending Main Thread");
}
}


/* AnotherClass.java */


//Inheriting from thread class
public class AnotherClass extends Thread
{
//Overrideing rum method from thread class
public void run()
{
System.out.println("Another Thread Started");

for (int j=0;j<=10 ;j++ )
{
System.out.println("Another "+j);

try
{
//sleep() method can be used here directly becz it is publicly inherited from Thread class
sleep(100);
}
catch (InterruptedException ex)
{
//Handling InterruptedException rather to declare becz overriding function cannot throw any new checked exception
System.out.println("Exception in AnotherClass thread : "+ex);
}
}
System.out.println("Ending Another Thread");
}
}



/**********OUTPUT***************/

Main Thread Started
Main 0
Another Thread Started
Another 0
Another 1
Another 2
Main 1
Another 3
Another 4
Another 5
Main 2
Another 6
Another 7
Another 8
Main 3
Another 9
Another 10
Ending Another Thread
Main 4
Main 5
Main 6
Main 7
Main 8
Main 9
Main 10
Ending Main Thread