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

标签 java multithreading multicore

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

这似乎在单处理器系统中工作,如果我调用Thread.currentThread() 或 sleep ,则只有当前正在运行的线程,它会返回或 sleep 。但是在多核系统中,可以同时运行多个线程,

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

最佳答案

Thread.currentThread() 方法返回我们当前正在运行的线程。这只是一种表达方式:“嘿,给我一个运行我的线程的引用”

假设我们有四核四线程A,B,C,D绝对并发运行,同时调用这个方法,它会根据我们当前所在的线程适当的返回A,B,C,D .

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

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.

关于java - 当有多个处理器时,Thread.currentThread() 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30024560/

相关文章:

linux - 多核处理器中基于轮询和中断的数据包处理方法

java - JPanel 中的 TitledBorder 在使用 translate() 方法时移动

java - 在JOOQ中使用PL/SQL函数

java - LdapInvalidDn异常 : unexpected token:

linux - Linux 线程中的文件段/节/记录锁

Java Lejos 自主 NXJ 机器人线程造成麻烦

c++ - 三重检查锁定?

java - Android - 获取附近地点的列表

java - 为什么这里抛出中断异常...原因?

java - 多核/并发编程和 .NET/Java