线程优先级
线程优先级是通过一个int 变量priority来控制的,优先级范围为1到10,可以通过setPriority(int)来设置,优先级默认为5。
以下是一个示例代码,
package thread;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class ThreadPriority {
private static volatile boolean notStart = true;
private static volatile boolean notEnd = true;
public static void main(String[] args) throws Exception {
List<Job> jobs = new ArrayList<Job>();
// 先给不同线程分别给一个不同的优先级并执行线程
for (int i = 0; i < 10; i++) {
int priority = i < 5 ? Thread.MIN_PRIORITY : Thread.MAX_PRIORITY;
Job job = new Job(priority);
jobs.add(job);
Thread thread = new Thread(job, "Thread:" + i);
thread.setPriority(priority);// 设置优先级
thread.start();
}
notStart = false;
TimeUnit.SECONDS.sleep(10);
notEnd = false;
for (Job job : jobs) {
System.out.println("Job priority:" + job.priority + " ,jobCount:" + job.jobCount);
}
}
static class Job implements Runnable {
// 线程优先级
private int priority;
private long jobCount;
// 设置优先级
public Job(int priority) {
this.priority = priority;
}
@Override
public void run() {
while (notStart) {// 如果线程是开着的,
/**
* Causes the currently executing thread object to temporarily pause and allow other threads to execute.
*/
Thread.yield();// 那么先停下来,让其他线程执行
}
while (notEnd) {
Thread.yield();
jobCount++;
}
}
}
}
打印出
Job priority:1 ,jobCount:2847305
Job priority:1 ,jobCount:1
Job priority:1 ,jobCount:16654503
Job priority:1 ,jobCount:9022916
Job priority:1 ,jobCount:2847155
Job priority:10 ,jobCount:9517759
Job priority:10 ,jobCount:11989979
Job priority:10 ,jobCount:9069022
Job priority:10 ,jobCount:24185755
Job priority:10 ,jobCount:9519740
由此可以看出,线程的优先级没有生效,很多优先级1和优先级10的job的技术结果并非常相近,没有明显差异,这表示程序正确性不能依赖线程的优先级的高低
欢迎关注公众号:Java后端技术全栈