Creating a simple thread using Runnable

Implementing the Runnable interface to carry out Multi Threading in Java.

class ChildThread implements Runnable
{
Thread t;
public ChildThread()
{
// Create a thread
t=new Thread(this);
// Set a name to child thread
t.setName("Child Thread");
// Start the thread
t.start();
}
public void run()
{
try
{
for(int i=5;i>=1;i--)
{
System.out.println(t.getName()+": "+i);
Thread.sleep(1000);
}
}catch(InterruptedException e){
System.out.println("Child thread interrupted.");
}
}
}
class ChildThreadDemo
{
public static void main(String args[])
{
// Get current thread's object
Thread mainThread=Thread.currentThread();
// Set a name to main thread
mainThread.setName("Main Thread");
// Create child thread object
new ChildThread();
// Start the loop
try
{
for(int i=5;i>=1;i--)
{
System.out.println(mainThread.getName()+": "+i);
Thread.sleep(1000);
}
}catch(InterruptedException e){
System.out.println("Main thread interrupted.");
}
}
}

------------------------------------------------
Output :
------------------------------------------------

Main Thread: 5
Child Thread: 5
Main Thread: 4
Child Thread: 4
Main Thread: 3
Child Thread: 3
Main Thread: 2
Child Thread: 2
Child Thread: 1
Main Thread: 1


Posted by at on

Tags: Multi Threading,