gpt4 book ai didi

java - 线程优先级没有影响

转载 作者:行者123 更新时间:2023-12-02 10:34:52 24 4
gpt4 key购买 nike

我正在用 Java 编写一个饥饿模拟。然而,当我运行它时,它几乎每次都不起作用。我正在 MacOS 上工作。代码如下:

public class StarvationNew {
private static SharedObject sharedObject = new SharedObject(); // to jest ten obiekt (operacja) na ktorym sie blokuje
private static volatile boolean isActive = true;

public static void main(String[] args) {
Thread t1 = new Thread(new Worker(), "Thread_1");
Thread t2 = new Thread(new Worker(), "Thread_2");
Thread t3 = new Thread(new Worker(), "Thread_3");

t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t3.setPriority(Thread.MIN_PRIORITY);

t1.start();
t2.start();
t3.start();


try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
isActive = false;

}

private static class Worker implements Runnable {
private int runCount = 0;

@Override
public void run() {
while(isActive) {
sharedObject.playOperation();
runCount++;
}
System.out.println("--------");
System.out.println(Thread.currentThread().getName() + " ended with: " + runCount);
System.out.println("--------");
}
}

}

SharedObject 只是模拟长时间运行的操作,如下所示:

public class SharedObject {
public synchronized void playOperation() {
try {
// long operations
System.out.println(Thread.currentThread().getName());
Thread.sleep(150);
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}

我想知道这段代码有什么错误。

最佳答案

使用 Java 线程时需要记住几件事。

  1. 线程优先级的规则高度依赖于系统。什么时候虚拟机依赖于宿主机的线程实现平台上,线程调度受该线程支配实现。
  2. 经验法则:在任何给定时间,最高优先级的线程是运行。然而,这并不能得到保证。 线程调度程序可能选择运行较低优先级的线程以避免饥饿。为了这原因,使用线程优先级仅影响调度策略效率目的。不要依赖它来保证算法的正确性。
  3. 如果有多个可运行线程具有相同的值,会发生什么情况?(最高优先级?选择最高优先级的线程之一。如何在两者之间进行仲裁完全取决于线程调度程序相同优先级的线程。 Java 编程语言没有给出确保所有线程都得到公平对待。

如上所述,我在 Windows 10 (Java 8) 计算机上没有看到以下输出有任何异常:

Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_1
Thread_3
--------
Thread_1 ended with: 34
--------
--------
Thread_2
Thread_3 ended with: 1
--------
--------
Thread_2 ended with: 1
--------

看看this了解更多详情。

关于java - 线程优先级没有影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53360962/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com