[英]Should you create an unlimited number of threads in Java?
我正在编写的程序要求用户输入不限数量的项目,而我的程序将对这些项目中的每一项进行处理。 我使程序在3个线程上执行此操作,因此它可以更快地完成。 使用我现在拥有的程序,它继续循环检查每个线程是否仍在运行,然后如果3个线程中没有1个正在运行,则会创建一个新线程。 我创建一个新线程的唯一原因是它说一个线程只能使用一次。 有一个更好的方法吗?
不,您不应该使用ThreadPool,幸运的是,Java已经包含了您所需要的所有东西: java.util.concurrent
使用具有10个并发线程的线程池的示例:
import java.io.PrintStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class ThreadsExample {
public static void main(String[] args) throws InterruptedException {
ExecutorService exec = Executors.newFixedThreadPool(10);
exec.awaitTermination(1, TimeUnit.SECONDS);
for (int i = 0; i < 100; i++) {
exec.submit(new MyTask(System.out));
}
exec.shutdown();
}
public static class MyTask implements Runnable {
PrintStream out;
public MyTask(final PrintStream out) {
this.out = out;
}
public void run() {
out.println("MyTask executed in : " + Thread.currentThread().getName());
}
}
}
查看java.util.concurrent.Executors
类以查找其他线程池实现(预定池,单线程池...。),您的任务也可以实现接口Callable
,该接口为异常捕获和返回对象提供了更多控制权从您的线程。
使用Executors
工厂类中的Java并发线程池之一,并设置可以从Runtime.getRuntime().availableProcessors();
获得的处理器数量Runtime.getRuntime().availableProcessors();
作为最大性能的线程池大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.