在 Java 中创建一个新线程有多昂贵?我们什么时候应该考虑使用线程池? [英] How expensive is creating of a new thread in Java? When should we consider using of a thread pool?

查看:51
本文介绍了在 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

这篇关于在 Java 中创建一个新线程有多昂贵?我们什么时候应该考虑使用线程池?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆