简体   繁体   English

Java - 管理大量线程与多核

[英]Java - Manage large number of threads versus multicore

I am currently dealing with a script which make some checks & insertions for each databases of a Mongo server.我目前正在处理一个脚本,它为 Mongo 服务器的每个数据库进行一些检查和插入。 It's multithreading.是多线程。

for (int i = 0; i < countDatabase; i++) {     
    new threadDatabase(database.get(i).toString()).start();            
}

Problem: I have 16 databases to parse...I am afraid the PC where the script will be set up, won't manage 16 (or more) threads...问题:我有 16 个数据库要解析...恐怕要设置脚本的 PC 无法管理 16 个(或更多)线程...

Any ideas how to deal a large number of threads?任何想法如何处理大量线程? I heard about pool, but not sure it can deal with database name I send as parameter...我听说过池,但不确定它是否可以处理我作为参数发送的数据库名称......

Thanks谢谢

16 threads isn't a lot of threads. 16个线程并不是很多线程。 Sure, it's probably more threads than you've got CPU cores, but if you're talking to a remote database, odds are you'll spend most of the time waiting for I/O to complete so CPU won't be a limiting factor.当然,它的线程数可能比 CPU 内核数多,但如果您正在与远程数据库通信,您可能会花费大部分时间等待 I/O 完成,因此 CPU 不会成为限制因素。

Apart from that, a thread pool would work just fine for you:除此之外,线程池对您来说也很好:

ExecutorService executorService = ...;
for (int i = 0; i < countDatabase; i++) {     
    final String dbName = database.get(i).toString();
    executorService.submit(new Runnable(){
        @Override
        public void run() {
            parseDatabase(dbName);
        }
    });
}

16 threads on a PC? PC 16 线程?

Looking at my Windows Task manager/Performance, it shows 1238 threads running.查看我的 Windows 任务管理器/性能,它显示有 1238 个线程正在运行。 It's not even breaking a sweat.它甚至没有流汗。 Top process is sidebar.exe - 66 threads.顶级进程是 sidebar.exe - 66 个线程。

OK, so you're running some other U**xy OS - 16 threads not likely to be a problem there either.好的,所以您正在运行其他一些 U**xy 操作系统 - 16 个线程也不太可能成为问题。

16 threads is nothing. 16个线程没什么。 If they are all CPU-intensive, the box will get loaded up but, hey, that's the point!如果它们都是 CPU 密集型的,那么盒子会被加载,但是,嘿,这就是重点!

Try a pool if you have to, maybe to try and improve performance, but don't do it just because you are afraid that 16 threads is too much for your OS.如果必须,请尝试使用池,也许是为了尝试提高性能,但不要仅仅因为担心 16 个线程对您的操作系统来说太多了。

Rgds, Martin Rgds,马丁

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

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