Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Does anyone have any insight into 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.

like image 467
gshx Avatar asked Oct 26 '10 17:10

gshx


4 Answers

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)

like image 85
Bozho Avatar answered Oct 19 '22 09:10

Bozho


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.

like image 25
Nathan Hughes Avatar answered Oct 19 '22 11:10

Nathan Hughes


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

like image 45
willcodejavaforfood Avatar answered Oct 19 '22 09:10

willcodejavaforfood


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.

like image 1
ColinD Avatar answered Oct 19 '22 10:10

ColinD