This looks suspiciously like homework, and has been answered about 100k times on the internet.
– Brian RoachAug 18 '12 at 17:44
2
@Darin: All the answers in the post you mentioned state why runnable should be used and the advantages it provides. My question is why does Java have Thread at all, what are the advantages of Thread class over Runnable interface?
– user892871Aug 18 '12 at 17:50
1
You can't start threads without the Thread class. Even if you have a class implementing Runnable you would still need to instantiate a thread, or use the ExecutorService, to create your thread.
– DanAug 18 '12 at 17:51
@Brian: This is not a homework and i found no answer that gives a satisfied explanation to my question.
– user892871Aug 18 '12 at 17:51
@user892871 - Try the Oracle tutorials. http://docs.oracle.com/javase/tutorial/essential/concurrency/runthread.html The paragraph at the bottom explains it succinctly. It really boils down to Java doesn't have multiple inheritance therefore except in the most simplest cases you want to use an interface for flexibility.
– Brian RoachAug 18 '12 at 17:58
2 Answers2
11
Thread is a class, and when you say start() you create a thread of execution which is attached to an instance of Thread class. Therun() method of Runnable is called making it execute the task on to the thread of execution, and the start() method returns quickly.
Runnable is the task that is assigned to the newly created thread of execution.
So, without the Thread class, you cannot run your Runnable.
Thread is a class and contains functionality - whereas Runnable is an interface, therefore just a "contract" for the implementing class to obey. As Runnable is just an interface you need to instantiate a thread to contain it. Whereas thread already contains the ability to spawn a thread.
Implementing Runnable is the suggested way because if you extend Thread you can't extend anything else (Java doesn't support multiple inheritance). You can have multiple interfaces on a class, therefore you could have Runnable + many others and also extend another base class
You take the thread from the instantiation of the Runnable and make it sleep - this.sleep()