以下实例演示了如何通过setpriority() 方法来设置线程的优先级:
/*
author by w3cschool.cc
simplepriorities.java
*/public class simplepriorities extends thread {
private int countdown = 5;
private volatile double d = 0;
public simplepriorities(int priority) {
setpriority(priority);
start();
}
public string tostring() {
return super.tostring() + ": " + countdown;
}
public void run() {
while(true) {
for(int i = 1; i < 100000; i++)
d = d + (math.pi + math.e) / (double)i;
system.out.println(this);
if(--countdown == 0) return;
}
}
public static void main(string[] args) {
new simplepriorities(thread.max_priority);
for(int i = 0; i < 5; i++)
new simplepriorities(thread.min_priority);
}}
以上代码运行输出结果为:
thread[thread-1,1,main]: 5
thread[thread-2,1,main]: 5
thread[thread-3,1,main]: 5
thread[thread-0,10,main]: 5
thread[thread-3,1,main]: 4
thread[thread-0,10,main]: 4
thread[thread-1,1,main]: 4
thread[thread-5,1,main]: 5
thread[thread-4,1,main]: 5
thread[thread-2,1,main]: 4
thread[thread-0,10,main]: 3
thread[thread-1,1,main]: 3
thread[thread-4,1,main]: 4
thread[thread-2,1,main]: 3
……
以上就是java 实例 - 线程优先级设置的内容。