java - 如果我们有足够的处理器来服务所有线程,Thread.yield() 会做任何事情吗?

标签 java multithreading concurrency java-threads thread-synchronization

如果我们在具有两个处理器的机器上运行两个线程,并且我们在其中一个线程中调用 Thread.yield(),是否有理由认为什么都不会发生(调度程序基本上会忽略该请求),因为我们有足够的处理器来服务正在运行的线程?

最佳答案

每当一个线程调用 Thread.yield() 方法时,它都会向线程调度程序提示它已准备好暂停其执行。线程调度程序可以随意忽略此提示。

如果有任何线程执行了 yield 方法,线程调度程序会检查是否有任何可运行(等待执行)的线程与该线程具有相同或更高的优先级。如果处理器发现任何具有更高或相同优先级的线程,那么它将切换到一个新线程。如果不是,则当前线程继续执行。

因为,在您的示例中,您有足够的处理器来服务所有线程(它们正在运行,而不是在可运行状态中等待); Thread.yield() 什么都不做,你的线程会继续执行。

来自 Microsoft DOTNet 的关于 Windows 的说明:

This method is equivalent to using platform invoke to call the native Win32 SwitchToThread function.

Yielding is limited to the processor that is executing the calling thread. The operating system will not switch execution to another processor, even if that processor is idle or is running a thread of lower priority. If there are no other threads that are ready to execute on the current processor, the operating system does not yield execution

因此在某些情况下可能会有警告。

关于java - 如果我们有足够的处理器来服务所有线程,Thread.yield() 会做任何事情吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56043933/

相关文章:

java - 从Java中的另一个对象获取空值,但在自己的类中获取值

java - 如何获取 selenium 上所有打开的窗口和浏览器的处理程序?

c# - 在新线程上运行简单函数的最佳方式?

c++ - 这是线程安全 Queue 类的正确方法吗?

objective-c - 核心数据: concurency conflict between save and fetch

java - 具有冲突的 GridLayout 的嵌套 SWT 复合 Material

java - org.springframework.beans.TypeMismatchException : Failed to convert value 'java.lang.String' to 'java.lang.Class' spring

c++ - 使用 pthread_t 作为映射中的键

linux - Linux 中进程的线程堆栈

node.js - sqlite last_insert_rowid 是原子的吗?