gpt4 book ai didi

java - 我将我的线程设置为比其他线程更高的优先级,但 CPU 时间似乎是随机的?

转载 作者:行者123 更新时间:2023-11-30 08:01:40 25 4
gpt4 key购买 nike

我将我的线程设置为比其他线程更高的优先级,但 CPU 时间似乎是随机的?下面是我的程序。

public class Main {

public static void main(String[] args){

Priority high=new Priority("High Priority");
Priority low=new Priority("Low Priority");
//set the priorities
high.thread.setPriority(Thread.NORM_PRIORITY + 2);
low.thread.setPriority(Thread.NORM_PRIORITY - 2);
//start the threads
high.thread.start();
low.thread.start();
try {
high.thread.join();
low.thread.join();
} catch(Exception e){
e.printStackTrace();
}
System.out.println("\nHigh Priority thread counted to"+high.count);
System.out.println("\nLow Priority thread counted to"+low.count);
}
}

我的线程类

public class Priority implements Runnable {
int count;
Thread thread;
static boolean stop = false;
static String currentName;

public Priority(String name){
thread = new Thread(this,name);
count = 0;
//Only one version of currentName as it is static
currentName = name;
}

//Begin the execution of the thread
@Override
public void run() {
System.out.println(thread.getName() + " Starting");
do {
//enter the thread increment the counter
count++;
if (currentName.compareTo(thread.getName()) != 0) {
currentName=thread.getName();
System.out.println("In " + currentName);
}
} while(stop == false && count < 10000000);
stop=true;
System.out.println("\n" + thread.getName() + " terminating.");
}
}

程序的输出各不相同有时我会得到

High Priority thread counted to10000000

Low Priority thread counted to6266009

其他时候我会得到

High Priority thread counted to4859068

Low Priority thread counted to10000000

最佳答案

在程序的大部分生命周期中,只有两个可运行的线程。如果您在具有两个或更多 CPU 的计算机上运行,​​那么这两个线程的优先级不会有任何区别。仅当要运行的线程多于可供它们运行的​​ CPU 时,优先级才重要。

关于java - 我将我的线程设置为比其他线程更高的优先级,但 CPU 时间似乎是随机的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37379466/

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