试图围绕 Java 并发进行思考,并且很难理解线程池、线程和它们正在执行的可运行“任务”之间的关系。
如果我创建一个具有 10 个线程的线程池,那么我是否必须将相同的任务传递给池中的每个线程,或者池中的线程实际上只是与任务无关的“工作无人机”可用于执行任何任务?
无论哪种方式,Executor/ExecutorService 如何将正确的任务分配给正确的线程?
试图围绕 Java 并发进行思考,并且很难理解线程池、线程和它们正在执行的可运行“任务”之间的关系。
如果我创建一个具有 10 个线程的线程池,那么我是否必须将相同的任务传递给池中的每个线程,或者池中的线程实际上只是与任务无关的“工作无人机”可用于执行任何任务?
无论哪种方式,Executor/ExecutorService 如何将正确的任务分配给正确的线程?
通常,线程池是用一个生产者-消费者队列实现的,所有池线程都在等待任务。Executor 不必分配任务,它所要做的就是将它们推送到队列中。一些线程,一个“与任务无关的工作无人机”,将弹出任务,执行它的“run()”方法,完成后,循环循环以再次在队列中等待更多工作。
If I create a thread pool with, say, 10 threads, then do I have to pass the same task to each thread in the pool, or are the pooled threads literally just task-agnostic "worker drones" available to execute any task?
More or less the latter. Any given task gets assigned to the next available thread.
Either way, how does an Executor/ExecutorService assign the right task to the right thread?
There is no such thing as the "right" thread. The task (i.e. the Runnable
) needs to be designed so that it doesn't matter which thread runs it. This is not normally an issue ... assuming that your application properly synchronizes access / updates to data that is potentially used by more than one threads.