简体   繁体   中英

Using new Thread(foo).start() in Java. Looking for Best Practices

In Call the method of Java class which implements runnable after creating its thread object @RNJ proposed launching a Java Thread as

SomeClass sc = new SomeClass();
new Thread(sc).start();

in order to being able to call sc's methods from the current thread.

To me two questions arise from this:

  1. How can sc's thread lifecycle methods be called in this construct (like stop())?
  2. Is this really a good practice for thread instantiation when one wants to be able to call the remote methods or is there a more elegant/cleaner solution?

1) You can't, you need to keep a reference to the newly created Thread, but that is just matter of rearranging the code a little.

SomeClass sc = new SomeClass();
Thread thread = new Thread(sc);
thread.start();

2) In my personal opinion is always cleaner to have something that implements Runnable (it implies that can be run, anywhere, and it's just that... something that "runs") than to create something that extends Thread and overwrites the run method. If you do that you are implying your SomeClass is a Thread (which is a very bold assumption, you probably just want something that can be run and that's it, a thread sounds like a not-nice abstraction, tighlty coupled to an implementation.).

In the very end both solutions are the same, but Runnable one is more elegant... and flexible! If you decide to change your implementation in the future so each of your tasks are not run in a new thread but in a shared Executor or a ThreadPool... you won't need to change anything on your Someclass if it extended Runnable.

Executor executor = Executors.newCachedThreadPool();
...
...
SomeClass sc = new SomeClass();
executor.execute(sc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM