调度线程时的 JVM 公平性
JVM fairness while scheduling threads
关于 JVM 在调度线程执行方面的公平性是否有任何假设?
对于下面的代码片段,是否可以只执行 "code A" 而忽略 B?
public static void main(String args[]) {
new Thread() {
public void run() {
for (;;) { /* code A */ }
}
}.start();
new Thread() {
public void run() {
for (;;) { /* code B */ }
}
}.start();
}
这个问题更像是一个理论问题 - 让我们假设两个线程都没有被阻塞或以其他方式鼓励调度程序切换上下文。
Are there any assumptions on how fair JVM is when it comes to scheduling threads for execution?
没有
For the below snippet, is it possible to have "code A" executed only, with B being ignored?
理论上是的。
实践中:
如果有一个(可用的)核心,我希望 OS 级别的线程调度程序对线程进行时间切片,以便每个线程获得大约 50% 的可用时间在日志项中
如果有多个(可用的)内核,我希望这两个线程能够并行 运行。
请注意,JLS 或 JVM 规范均未提及线程调度或公平性。 Thread
.
的 javadoc 也没有
据我所知,唯一提到公平的 Java API 是 ReentrantLock
API (javadoc),其中有一个构造函数参数使用公平策略创建锁。这意味着调度程序会偏爱在锁上等待时间最长的线程。但即使这样也要注意:
"Note however, that fairness of locks does not guarantee fairness of thread scheduling."
关于 JVM 在调度线程执行方面的公平性是否有任何假设?
对于下面的代码片段,是否可以只执行 "code A" 而忽略 B?
public static void main(String args[]) {
new Thread() {
public void run() {
for (;;) { /* code A */ }
}
}.start();
new Thread() {
public void run() {
for (;;) { /* code B */ }
}
}.start();
}
这个问题更像是一个理论问题 - 让我们假设两个线程都没有被阻塞或以其他方式鼓励调度程序切换上下文。
Are there any assumptions on how fair JVM is when it comes to scheduling threads for execution?
没有
For the below snippet, is it possible to have "code A" executed only, with B being ignored?
理论上是的。
实践中:
如果有一个(可用的)核心,我希望 OS 级别的线程调度程序对线程进行时间切片,以便每个线程获得大约 50% 的可用时间在日志项中
如果有多个(可用的)内核,我希望这两个线程能够并行 运行。
请注意,JLS 或 JVM 规范均未提及线程调度或公平性。 Thread
.
据我所知,唯一提到公平的 Java API 是 ReentrantLock
API (javadoc),其中有一个构造函数参数使用公平策略创建锁。这意味着调度程序会偏爱在锁上等待时间最长的线程。但即使这样也要注意:
"Note however, that fairness of locks does not guarantee fairness of thread scheduling."