LabProgram11
LabProgram11
Write a java program to illustrate creation of threads using runnable class (start
method starts each of the newly created threads inside run method. There is a
sleep for suspend the thread for 500 milliseconds).
Solution:
class Counter implements Runnable
{
Thread t;
String name;
Counter ()
{
t = new Thread(this,"Counter");
System.out.println("Thread Created:counter");
}
Counter (String name)
{
this.name=name;
t= new Thread(this,name);
System.out.println("Thread Created:"+name);
}
void start ()
{
t.start();
}
public void run ()
{
int i;
try
{
for (i=1; i<=5; i++)
{
System.out.println("Thread"+name+":"+i);
Thread.sleep(500);
}
}
catch (InterruptedException e)
{
System.out.println("Exception caught");
}
}
}
public class ThreadDemo {
public static void main(String[] args)
{
Counter c1= new Counter("Counter1");
Counter c2= new Counter("Counter2");
Counter c3= new Counter("Counter3");
c1.start();
c2.start();
c3.start();
}
}
Output: