且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java - 线程和CPU之间的关系

更新时间:2023-12-04 11:00:46


这是否可以保证每个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.