调度线程时的java JVM公平性
在调度线程执行时,JVM是否公平
对于下面的代码段,是否可以只执行“代码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();
}
这个问题更多的是一个理论上的问题——让我们假设两个线程都不会被阻塞,或者以其他方式鼓励调度器切换上下文
# 1 楼答案
没有
理论上是的
实际上:
如果有一个(可用的)内核,我希望操作系统级的线程调度程序对线程进行时间切片,以便每个线程在日志项中获得大约50%的可用时间
如果有多个(可用)内核,我希望这两个线程并行运行
请注意,JLS或JVM规范都没有提到线程调度或公平性。对于
Thread
的javadoc也是如此据我所知,唯一提到公平性的Java API是
ReentrantLock
API(javadoc),其中有一个构造函数参数,用于创建具有公平性策略的锁。这意味着调度程序支持在锁上等待时间最长的线程。但就连这一点也值得注意: