Here, we define a class that implements Runnable interface. The Runnable interface has only one method, run( ), that is to be implemented by the class. This procedure becomes mandatory when the class already extends another class and to be made as a thread. It includes the following steps:
1. Declare a class that implements Runnable interface.
2. Implement the run( ) method.
3. Create a thread by defining an object that is instantiated from this "runnable" class or create Thread class object within that class.
4. Call the thread's start( ) method to run the thread.
The following program creates a thread by implementing Runnable interface
class MyThread implements Runnable
{
Thread t;
String s;
MyThread(String ss)
{
t=new Thread(this);
s=ss;
}
public void run()
{
for(int i=1;i<=3;i++)
{
System.out.println(s+i);
try { Thread.sleep(1000); } catch(Exception e) { }
}
}
}
class Test
{
public static void main(String as[])
{
MyThread t1=new MyThread("Alpha");
MyThread t2=new MyThread("Beta");
t1.t.start();
t2.t.start();
}
}
The above program generates the following output:
Alpha1
Beta1
Alpha2
Beta2
Alpha3
Beta3
0 comments:
Post a Comment