How many ways are for creating a new thread in Java?

后端 未结 7 2145
清歌不尽
清歌不尽 2020-12-29 10:14

Actually, what other ways are available apart from extending the Thread class and implementing the Runnable interface?

7条回答
  •  温柔的废话
    2020-12-29 10:39

    There is exactly one way to create a new thread in Java and that is to instantiate java.lang.Thread (to actually run that thread you also need to call start()).

    Everything else that creates threads in Java code falls back to this one way behind the cover (e.g. a ThreadFactory implementation will instantiate Thread objects at some point, ...).

    There are two different ways to specify which code to run in that Thread:

    • Implement the interface java.lang.Runnable and pass an instance of the class implementing it to the Thread constructor.
    • Extend Thread itself and override its run() method.

    The first approach (implementing Runnable) is usually considered the more correct approach because you don't usually create a new "kind" of Thread, but simply want to run some code (i.e. a Runnable) in a dedicated thread.

提交回复
热议问题