Here, we create a thread class that extends Thread class and override its run() method with the code required by the thread. This gives us access to all the thread methods directly. It includes the following steps:
1. Declare the class as extending the Thread class.
2. Override the run( ) method that defines the task of the thread
3. Create a thread object and call the start( ) method to initiate the thread execution.
The following program creates a thread by extending Thread class
class MyThread extends Thread
{
String s;
MyThread(String ss)
{
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.start();
t2.start();
}
}
The above program generates the following output:
Alpha1
Beta1
Alpha2
Beta2
Alpha3
Beta3
0 comments:
Post a Comment