Is this a topic that will be approved by the Contractor here?

As far as I understand, executors help handle the execution of runnables. For instance. I would choose to use an artist when I have several workflows that do their work and then complete the work. The contractor will handle the creation and completion of the flows necessary for the execution of working stocks.

However, now I am faced with a different situation. A fixed number of classes / objects should encapsulate their own stream. Thus, the thread starts when these objects are created, and the stream continues to work throughout the life time of these objects. Several objects, in turn, are created at the beginning of the program and exist throughout the execution time. I think that Threads is preferable to Executors in this situation, however, when I read the Internet, everyone seems to suggest using Executors over Threads in any possible situation.

Can someone please tell me if I want to choose artists or themes here and why?

thanks

+6
source share
3 answers

Without knowing more about the context, it is difficult to give a good answer, but, generally speaking, I would say that situations that require the use of Thread are quite small and far from each other. If you start trying to synchronize your program “manually” using synchronized , I’m sure that everything will quickly get out of hand. (Not to mention how difficult it will be to debug the code.)

Last time I used the stream when I wanted to record some kind of sound in the background. It was a start / stop, not a task-oriented one. (I tried my best to try and find an audio library that encapsulated this for me, but failed.)

If you decide to go for a streaming solution, I suggest that you try to limit the scope of the stream to only be executed on the associated object. This will, as far as possible, not make you think about what happened - before a relationship, thread-safe publication of values, etc. In the whole code.

+1
source

You mix things up a bit. Executor is just an interface. Thread is the main class. There is nothing that directly implies that Executor implementations perform tasks in separate threads.

Read the first few lines of JavaDoc.

Executor

So, if you need full control, just use Thread and do something yourself.

+3
source
  • ExecutorService may have a thread pool

It optimizes performance because creating Thread is expensive.

  • ExecutorService has life cycle control

shutdown() , shutdownNow() , etc.

  • ExecutorService is flexible.

You can use different types of behavior: configure ThreadFactory , set thread pool size, ScheduledThreadPoolExecutor delay behavior, etc.

+1
source

Source: https://habr.com/ru/post/982348/


All Articles