繁体   English   中英

如何使用 java 中的线程池使用特定线程执行特定任务

[英]how to use specific thread execute specific task using threadpool in java

我想使用线程池来执行具有不同字段的任务。 为了保持结果正确,我必须使用特定线程来执行具有特定字段的任务。 我怎样才能做到这一点?

您可以使用 ExecutorService 创建线程池。

ExecutorService executorService = Executors             
       .newFixedThreadPool(Runtime.getRuntime().availableProcessors());

然后创建一个任务列表,所有任务都将具有特定的字段。

List<Tasks> tasks; //This will contain all the type of tasks. 
//Tasks should be Runnable or callable depending on what you want
//if you want a return use Callable else Runnable.

在您的执行器服务执行方法中传递所有这些任务。

tasks.forEach(executorService::execute);

这可能会有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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