gpt4 book ai didi

java - 为什么两个最低和最高优先级的线程仍然交错?

转载 作者:行者123 更新时间:2023-12-02 02:56:12 25 4
gpt4 key购买 nike

考虑拥有以下类(class):

public class RunnableDemo implements Runnable {
private Thread t;
private String threadName;

RunnableDemo( String name) {
threadName = name;
System.out.println("Creating thread " + threadName );
}

@Override
public void run() {
System.out.println("Running thread" + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread " + threadName + ", iteration: " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println(threadName + " exiting.");
}

public void Fire (int priority) {
System.out.println("Starting thread " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.setPriority(priority);
t.start ();
}
}
}

还有另一个类来测试它:

public class TestThread {

public TestThread() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
RunnableDemo R1 = new RunnableDemo( "RunnableDemo-One");
RunnableDemo R2 = new RunnableDemo( "RunnableDemo-Two");

R1.Fire(Thread.MAX_PRIORITY);
R2.Fire(Thread.MIN_PRIORITY);
}

}

此代码片段运行时的输出为:

Creating thread RunnableDemo-One
Creating thread RunnableDemo-Two
Starting thread RunnableDemo-One
Starting thread RunnableDemo-Two
Running threadRunnableDemo-One
Thread RunnableDemo-One, iteration: 4
Running threadRunnableDemo-Two
Thread RunnableDemo-Two, iteration: 4
Thread RunnableDemo-Two, iteration: 3
Thread RunnableDemo-One, iteration: 3
Thread RunnableDemo-Two, iteration: 2
Thread RunnableDemo-One, iteration: 2
Thread RunnableDemo-Two, iteration: 1
Thread RunnableDemo-One, iteration: 1
RunnableDemo-Two exiting.
RunnableDemo-One exiting.

换句话说,尽管一个线程具有 MAX_PRIORITY,另一个线程具有 MIN_PRIORITY,系统仍然在它们之间交错,就好像它们具有相同的优先级一样。 这是为什么

以不同的方式表述同一问题:是否存在程序输出的场景或代码修改:

Thread RunnableDemo-One, iteration: 4
Thread RunnableDemo-One, iteration: 3
Thread RunnableDemo-One, iteration: 2
Thread RunnableDemo-One, iteration: 1

Thread RunnableDemo-Two, iteration: 4
Thread RunnableDemo-Two, iteration: 3
Thread RunnableDemo-Two, iteration: 2
Thread RunnableDemo-Two, iteration: 1

也就是说,同时仍然将它们保持为单独且独立的线程?

最佳答案

JVM 将线程呈现给操作系统,这里优先级再次根据 JVM 调度算法发挥作用,但最终由操作系统决定,因此,它自己的算法会尝试在多个 CPU 核心周期中尽可能多地使用正在争夺资源的线程。

但是,如果在某个用例中您希望一个线程在第二秒之前完成,则可以考虑使用 join()。

关于java - 为什么两个最低和最高优先级的线程仍然交错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43043999/

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