Q) Write a program that user defined class implements java.long.Runnable interface instead of extending thread class.
A)
Note:
->whenever user defined thread class implements Runnable interface, instantiate java.long.Thread class to create the Thread object. Make use of Runnable interface as argument taking constructor of Thread class. Supply user defined Thread class reference as argument to the Thread class constructor.
// RunnableExample.java
class Mythreadone implements Runnable
{
public void run()
{
for (int i=1;i<=30;i++)
{
System.out.println(i);
try
{
Thread.sleep(400); // suspended y=the Thread, not technically required.
}
catch(Exception e)
{
}
}
}
}
class MyThreadTwo implements Runnable
{
public void run()
{
for(int i=70;i<=100;i++)
{
System.out.println(i);
try
{
Thread.sleep(400); // initially suspended.
}
catch(Exception e)
{
}
}
}
}
class RunnableExample {
public static void main(String[] args) {
Thread t1=new Thread(new Mythreadone());
Thread t2=new Thread(new MyThreadTwo());
t1.setPriority(7); //not technically required.
t1.start();
t2.start();
}
}
-> start () method belongs to Thread class. So, if our class is implements Runnable then it will not working, error will raised.
->to avoid this problem we create Runnable interface of its child class object then that object reference is passed as argument to the Thread class, so, then only start method is called.
->Runnable is an interface that’s why its child class object is created.
Note:
->whenever user defined class is required to inherit from another class and at the same time multithreading also should be implemented in that class, we go for Rubnnable interface.
->whenever user defined class is required to inherit from another class and at the same time multithreading also should be implemented in that class, we go for Rubnnable interface.
Ex:
Class A extends B implements Runnable
{
}
->Because at a time we can’t extend 2 classes in java. So, A can’t inherit B and Thread class, so, A is extends B and Runnable is implemented.
Comments
Post a Comment