5

Possible Duplicate:
Java: “implements Runnable” vs. “extends Thread”

  1. Why does Java language provide both Thread and Runnable?
  2. What are the advantages of thread over runnable ( why couldnt Java just provide a runnable)
  3. Can we make a runnable sleep, give it an id etc?
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
user892871
  • 1,025
  • 3
  • 13
  • 28
  • 3
    This looks suspiciously like homework, and has been answered about 100k times on the internet. – Brian Roach Aug 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? – user892871 Aug 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. – Dan Aug 18 '12 at 17:51
  • @Brian: This is not a homework and i found no answer that gives a satisfied explanation to my question. – user892871 Aug 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 Roach Aug 18 '12 at 17:58

2 Answers2

11
  1. 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.

  2. Runnable is the task that is assigned to the newly created thread of execution.

  3. So, without the Thread class, you cannot run your Runnable.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
4
  1. 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.
  1. 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

  2. You take the thread from the instantiation of the Runnable and make it sleep - this.sleep()

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Dan
  • 1,030
  • 5
  • 12