// Simple multiple thread demonstration using the Runnable interface
class MultiThread
{
public static void main(String args[])
{
MultiRun nrf = new MultiRun("first thread");
MultiRun nrs = new MultiRun("second thread");
MultiRun nrt = new MultiRun("third thread");
try
{
Thread.sleep(10000); //put main thread to sleep yeild the CPU
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
class MultiRun implements Runnable //create a new thread class
{
Thread rt;
String name;
MultiRun(String threadname)
{
name = threadname;
rt = new Thread(this, name);
System.out.println( "Child thread: " + rt);
rt.start();
}
// once a thread is started this is the entry point for subsequent time slices
public void run()
{
try
{
for(int i=5; i>0; i--)
{
System.out.println(name+": " + i);
rt.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("Child thread interrupted.");
}
System.out.println("exiting Child thread " + name);
}
}
|