1)How do we create a
thread using Runnable interface? Whether I need to call run() method of Runnable interface? What is the advantage of using Runnable interface instead of extending Thread class?
2)If I created a thread using Runnable interface and creating an object of it and passing to Thread Object, How can I call start method on different object ?
ClassRunnable objRunnable = new ClassRunnable ();
Thread t = new Thread (objRunnable);
t.start (); How I know the above code used for a particular thread ?
run()
1)the thread can execute its own run() method
2)the thread can execute the run() method of some other object
If you want the thread to execute its own run() method ,you need to subclass the Thread class and give your subclass a run()
Public class Counter extends Thread
{
public void run()
{
for(int i)
}
}
The run method just print 1.10 .To do this in a Thread, you first construct an instance of Counter and then invoke its start() method
1.Counter ct = new Counter();
2.ct.start() //start not run
What you do not do is call run() directly, instead you call start()The start() registers the thread (that is,ct) with thread scheduler.
If you want your thread to execute the run() method of some other object than itself, you still need to construct an instance of the Thread class. The only difference is that when you call the Thread constructor, you have to specify which object owns the run() method that you want
Public class Counter implements Runnable
{
public void run()
{
for(int i)
}
}
This class does not extend the Thread class, However, it has a run() method and it declares that it implements the Runnable interface. Thus any instance of the Counter class is eligible to be passed .
1.Counter c = new Counter();
2.Thread t = new Thread();
3.t.start();
Why Runnable rather than extending thread class ?
The run() method ,like any other member method ,is allowed to access the private data, and call private method, of the class of which it is a member. Putting run() in a subclass of Thread may mean that the method cannot get to features it needs .
Could somone throw light on the above statemnt?
2) Thread is the single implementation