当有多个处理器时,Thread.currentThread() 是如何工作的?

How does Thread.currentThread() work when there are multiple processors?

Thread.currentThread()可以用来获取当前正在执行的线程。而且我认为 sleep 和 yield 方法都是静态的,因为它们不能在其他线程上执行 sleep 或 yield 。因此,通过将它们设置为静态,它将休眠或仅产生当前正在执行的线程。

这似乎在单处理器系统中工作,如果我调用Thread.currentThread() 或睡眠然后只有当前 运行ning 线程,它将 return 或它会睡眠。但是在多核系统中,多个线程可以同时运行,

那么 Thread.currentThread()Thread.sleep() 是如何工作的...?

它仅适用于 "current" 线程。在多核系统中,如果您的代码是单线程的,则只有一个线程是 运行,这是当前线程,因此此代码将在该线程上运行。如果你有多线程程序,这段代码将在它被调用的线程中工作。内核的数量并不重要。 Java 将线程和负载分配给不同的内核,但从代码的角度来看,处理器数量并不重要。

这些方法是静态的,因为您可以访问正在执行该代码的core/CPU的当前执行线程

如果有一个以上的核心或 CPU 个处理器,通过此代码的每个核心都会 return 给你自己的线程。

因此您无需关心系统中有多少cores/CPUs,这些方法在单核和多核系统两种情况下都适用。

请记住,Java Thread 是 OS 真实线程(posix、windows...)的抽象,因此您可以编写自己的代码不关心 OS 架构的程序。

这种情况下的文档很差。 Thread.currentThread() returns 实际上是你执行那行代码的线程。所以在这种情况下你是否处于多处理器环境中并不重要。

当你有两个线程ThreadAThreadB运行完全并行,你同时请求Thread.currentThread()你会得到对应的线程这是在哪里执行的。

方法Thread.currentThread() return是我们目前运行里面的线程。这只是一种表达方式:"Hey give me a reference of the thread that is running me"

假设我们有四核四线程A,B,C,D运行绝对并发,同时调用这个方法,会returnA,B,C和D 适当地基于我们当前所在的线程。

方法 Thread.currentThread().sleep()Thread.sleep() 基本上做同样的工作。根据 currentThread() 的 documentation:

public static Thread currentThread()

Returns a reference to the currently executing thread object.

public static void sleep(long millis)throws InterruptedException

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.