Why should I use Runnable instead of Thread?
This question already has an answer here:
1. Java doesn't support multiple inheritance, which means you can only extend one Java class, so once you extended Thread
class you lost your chance and cannot extend(inherit) another class in java.
2. In OOP extending a class generally means adding new functionality, modifying or improve behaviors. If you are not making any modification on Thread
, then use Runnable
interface instead.
3. Implementing Runnable
makes your class more flexible(you can implement more than one interface).
One of the big advantages is: you don't have to run a Runnable
on a new thread.
One day, you might decide that instead of running it on a new thread, you should run it directly (on the current thread), or on a thread pool - and then you can change new Thread(runnable).start()
to threadPool.submit(runnable)
or runnable.run()
- and the change only affects one place.
Also, if you leave a Runnable
hanging around, it doesn't waste resources - it doesn't count towards the thread limit (if there is one), and it doesn't reserve space for a stack. Say you wanted to have a queue of things to do one at a time - sure, you could have a Queue<Thread>
and then start each thread when the previous one finished, but then you're wasting a lot of memory with non-running threads. If you used a queue of Runnable
s, you don't use as much memory except when they're actually running.
上一篇: 有关实现Runnable的问题