The first method inherits the Thread class and the second method implements the Runnable interface.
Method 1 (inheriting the Thread class ):
Java code
Package com. demo. thread;
Public class ThreadDemo1 extends Thread
{
Private int count = 5;
// Only initialize once
Private static int threadCount = 0;
Private int threadNumber = ++ threadCount;
Public ThreadDemo1 ()
{
System. out. println ("Making" + threadNumber );
}
Public void run ()
{
While (true)
{
System. out. println ("Thread" + threadNumber + "(" + count + ")");
If (-- count = 0)
{
Return;
}
}
}
Public static void main (String [] args)
{
For (int I = 0; I <5; I ++)
{
New ThreadDemo1 (). start ();
}
System. out. println ("All threads started! ");
}
}
Method 2 (implementing the Runnable interface ):
Java code
Package com. demo. thread;
Public class ThreadDemo2 implements Runnable
{
Private int count = 5;
Private static int threadCount = 0;
Private int threadNumber = ++ threadCount;
Public ThreadDemo2 ()
{
System. out. println ("Making" + threadNumber );
}
Public void run ()
{
While (true)
{
System. out. println ("Thread" + threadNumber + "(" + count + ")");
If (-- count = 0)
{
Return;
}
}
}
Public static void main (String [] args)
{
For (int I = 0; I <5; I ++)
{
ThreadDemo2 td = new ThreadDemo2 ();
New Thread (td). start ();
}
System. out. println ("All Threads started! ");
}
}