Java - 线程和CPU之间的关系 [英] Java - relationship between threads and CPUs

查看:291
本文介绍了Java - 线程和CPU之间的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是多线程的新手,我正在开发一个项目,我试图在我的Java程序中使用4个CPU。我想做类似的事情

I am pretty new to multithreading, and I am working on a project where I am trying to utilize 4 CPUs in my Java program. I wanted to do something like

int numProcessors = Runtime.getRuntime().availableProcessors();
ExecutorService e = Executors.newFixedThreadPool(numProcessors);

这是否可以保证每个CPU都有一个线程工作?在我创建线程时,系统不会很忙,但是一段时间后它会非常繁忙。我认为操作系统会选择最不繁忙的CPU来创建线程,但是如果它们在创建时都没有特别忙,它是如何工作的?

Will this guarantee that I will have one thread working per CPU? At the time that I create the threads, the system will not be busy, however some time afterwards it will be extremely busy. I thought that the OS will pick the least busy CPU to create the threads, but how does it work if none of them are particularly busy at the time of creation?

,线程池服务应该重用线程,但如果它看到另一个CPU上有更多的可用性,它会杀死线程并在那里产生一个新线程吗?

Also, the thread pool service is supposed to reuse threads, but if it sees there is more availability on another CPU, will it kill the thread and spawn a new one there?

推荐答案


这是否可以保证每个CPU都有一个线程工作?

Will this guarantee that I will have one thread working per CPU?

如果你有四个需要同时执行的任务,你可以期望它们各有一个线程。在HotSpot JVM中,它创建Thread对象,它是创建池时实际线程的代理。创建实际线程时,以及如何对您起作用。

If you have four tasks which need to be executed at the same time, you can expect them have a thread each. In the HotSpot JVM, it creates the Thread object which are proxies for the actual thread when you create the pool. When the actual threads are created, and how, does matter to you.


在创建线程时,系统不会很忙,不过一段时间之后会非常忙碌。我认为操作系统会选择最不繁忙的CPU来创建线程,但是如果它们在创建时都没有特别忙,它是如何工作的?

At the time that I create the threads, the system will not be busy, however some time afterwards it will be extremely busy. I thought that the OS will pick the least busy CPU to create the threads, but how does it work if none of them are particularly busy at the time of creation?

线程由操作系统创建,并添加到要安排的线程列表中。

Threads are created by the OS and it is added to the list of threads to schedule.


此外,线程池服务应该重用线程,但如果它看到另一个CPU上有更多的可用性,它会杀死线程并在那里产生一个新线程吗?

Also, the thread pool service is supposed to reuse threads, but if it sees there is more availability on another CPU, will it kill the thread and spawn a new one there?

Java在这件事上没有发言权。操作系统决定。它不会杀死并重新启动线程。

Java has no say in the matter. The OS decides. It doesn't kill and restart threads.

线程与您建议的方式不依赖于CPU。操作系统根据需要运行的线程和哪些CPU是空闲的,在CPU之间传递线程。

Threads are not tied to CPUs in the way you suggest. The OS passes threads between CPUs based on which one threads need to run and which CPUs are free.

这篇关于Java - 线程和CPU之间的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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