Why do you create a Thread
in the first place?
Your code should implement the Runnable
interface instead.
Then, when you decide that you want to run it in a thread, simple instantiate a Thread
with the Runnable
as the argument and call start()
on the Thread
object.
If, instead, you just want to run it in your current thread, simply call run()
on your Runnable
object.
This has several advantages:
- you don't involve any
Thread
objects as long as you don't care about separate threads
- your code is wrapped in a
Runnable
which fits closer conceptually: you're not writing some special kind of Thread, do you? You simply write some code that can be executed/run.
- you can easily switch to using an
Executor
which further abstract away the decision
And last but not least you avoid any potential confusion on whether or not a native thread resource is created.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…