开发者

Benefits of public modifier on Java Thread's run()

Does anyone have any insight i开发者_如何学Pythonnto the history of Java Thread class's run() method being public? Almost all the time, it gets used by overriding and thus would the protected modifier have been more appropriate? That would still leave the start() as the public api for users and thus not leave any room for mistakes with users calling run() accidentally.


Thread implements Runnable, which defines the run() method, so it has to be public.

But since Java 1.5 is advisable to use the Executors services instead of java.lang.Thread. Executors are decoupling the unit of work to be executed (Runnable, Callable) from the actual executor. (With Thread they were the same thing)


You are better off not overriding Thread, you should create a Runnable and pass it into the constructor for the new Thread. That way the work being done, the Runnable, is kept separate from the implementation mechanism, the Thread.


run is defined in the Runnable interface and all methods defined in an interface are public.


I think it's basically a bad design that, in the interest of making things "simple" for the user, allowed coupling the task to be run (the Runnable) to the thread to run it on directly. Since Thread was added in JDK 1.0, though, that design hasn't been able to be changed since then, just deprecated (sort of) in favor of the Executor framework. JDK 1.0 was a long time ago, and various mistakes were made without the benefit of experience since then.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜