优先级较高的线程与优先级较低的线程获得相同的 CPU 数量?
Higher priority thread getting the same CPU amount as the lower priority?
以下是我的代码。
public class Test {
public static void main(String[] args) throws InterruptedException {
PrintingThread a = new PrintingThread("A");
a.setPriority(9);
PrintingThread b = new PrintingThread("B");
b.setPriority(1);
a.start();
b.start();
}
static class PrintingThread extends Thread {
private int i = 0;
private String name;
public PrintingThread(String name) {
super();
this.name = name;
}
@Override
public void run() {
while (true) {
i++;
if (i % 100000 == 0) {
System.out.println("Thread " + name + " count=" + i
+ ". Time :" + System.currentTimeMillis());
}
}
}
}
}
由于我给A设置了更高的优先级,所以我预计打印语句会给A更高的值,但事实并非如此。以下是 运行 程序一段时间后的示例输出。
Thread A count=1033300000. Time :1431937330486
Thread A count=1033400000. Time :1431937330486
Thread A count=1033500000. Time :1431937330486
Thread A count=1033600000. Time :1431937330486
Thread B count=1058600000. Time :1431937330485
Thread B count=1058700000. Time :1431937330487
我正在使用 Ubuntu 和 运行 Java 版本 1.7.0-79-b15。
我运行程序使用命令
taskset 0x00000001 java -jar Untitled.jar
并已使用系统监视器 UI 验证仅使用了一个 CPU(如果我执行命令 java -jar Untitled.jar
使用了两个 CPU)。
这是不是说我设置了优先级也没有区别?还是我的程序有问题?
你的程序没问题。
设置线程优先级只是对底层OS(来自您的代码)的提示,要求它尝试增加线程的优先级。无法保证(甚至没有必要)OS 会根据您的调用执行某些操作。
如果此程序在不同环境(CPU 负载)或不同平台(但 预期 结果可能不一致)。
注意:在 Linux 系统上,默认情况下 不考虑 线程优先级。您必须使用 XX:ThreadPriorityPolicy
选项在 Linux、
上启用 线程优先级
以下是我的代码。
public class Test {
public static void main(String[] args) throws InterruptedException {
PrintingThread a = new PrintingThread("A");
a.setPriority(9);
PrintingThread b = new PrintingThread("B");
b.setPriority(1);
a.start();
b.start();
}
static class PrintingThread extends Thread {
private int i = 0;
private String name;
public PrintingThread(String name) {
super();
this.name = name;
}
@Override
public void run() {
while (true) {
i++;
if (i % 100000 == 0) {
System.out.println("Thread " + name + " count=" + i
+ ". Time :" + System.currentTimeMillis());
}
}
}
}
}
由于我给A设置了更高的优先级,所以我预计打印语句会给A更高的值,但事实并非如此。以下是 运行 程序一段时间后的示例输出。
Thread A count=1033300000. Time :1431937330486
Thread A count=1033400000. Time :1431937330486
Thread A count=1033500000. Time :1431937330486
Thread A count=1033600000. Time :1431937330486
Thread B count=1058600000. Time :1431937330485
Thread B count=1058700000. Time :1431937330487
我正在使用 Ubuntu 和 运行 Java 版本 1.7.0-79-b15。 我运行程序使用命令
taskset 0x00000001 java -jar Untitled.jar
并已使用系统监视器 UI 验证仅使用了一个 CPU(如果我执行命令 java -jar Untitled.jar
使用了两个 CPU)。
这是不是说我设置了优先级也没有区别?还是我的程序有问题?
你的程序没问题。
设置线程优先级只是对底层OS(来自您的代码)的提示,要求它尝试增加线程的优先级。无法保证(甚至没有必要)OS 会根据您的调用执行某些操作。
如果此程序在不同环境(CPU 负载)或不同平台(但 预期 结果可能不一致)。
注意:在 Linux 系统上,默认情况下 不考虑 线程优先级。您必须使用 XX:ThreadPriorityPolicy
选项在 Linux、