Advantage of Thread over Runnable
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?
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. The run()
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.
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.
2) 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
3) you take the thread from the instantiation of the Runnable and make it sleep - this.sleep()
链接地址: http://www.djcxy.com/p/92068.html上一篇: 为什么我应该使用Runnable而不是Thread?
下一篇: 线程优于Runnable