Creating a simple thread using Runnable ~ foundjava
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: 5Child Thread: 5Main Thread: 4Child Thread: 4Main Thread: 3Child Thread: 3Main Thread: 2Child Thread: 2Child Thread: 1Main Thread: 1
No comments:
Post a Comment