在 Java 中创建一个新线程有多昂贵?我们什么时候应该考虑使用线程池?
我想知道应该使用线程池的边缘在哪里.在不使用线程池的情况下,我每秒可以创建多少个新线程仍然避免明显的性能损失?
I wonder where is the verge after which a thread pool should be used. How many new threads per second can I create without using a thread pool still avoiding noticeable performance penalty?
是否有任何可观察的开源线程池实现?
Are there any observable open-source thread-pool implementations?
您应该始终使用线程池.java.util.concurrent 包不仅为您提供了性能,还为您提供了易用性.在 Java 5 及更高版本中,内置了线程池.
You should always use a thread pool. Not just for performance, but for the ease of use the java.util.concurrent package gives you. With Java 5 and later, thread pooling is built in.
不要考虑线程",而是使用 Executor 接口来执行你需要执行的任务.创建一个新的线程池很简单:
Instead of thinking in terms of 'threads', use the Executor interface to execute tasks you need to be performed. Creating a new thread pool is as simple as:
Executor executor = Executors.newFixedThreadPool(5);
关于 java.util.concurrent 包的完整文档在这里:http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-frame.html
Full documentation on the java.util.concurrent package is here: http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-frame.html