本节摘要:介绍线程优先级,代码示例
一、线程优先级
线程优先级的范围是1~10,默认优先级是5,线程优先级的主要作用是让调度器优先调度高优先级线程,但这不意味着低优先级线程得不到执行,通常情况不需要修改线程优先级,Thread类中有3个优先级的常量:
二、源码分析
public final void setPriority(int newPriority) {
ThreadGroup g;//线程所属的线程组
checkAccess();
//设置的级别不能大于10且不能小于1
if (newPriority > MAX_PRIORITY || newPriority < MIN_PRIORITY) {
throw new IllegalArgumentException();
}
if((g = getThreadGroup()) != null) {
//设置的级别不能大于所属线程组的最大级别
if (newPriority > g.getMaxPriority()) {
newPriority = g.getMaxPriority();
}
setPriority0(priority = newPriority);//本地方法
}
}
三、线程优先级示例
public class ThreadPrioritiesDemo extends Thread {
private int priority;
public ThreadPrioritiesDemo(String name, int priority) {
super(name);
this.priority = priority;
}
public static void main(String[] args) {
Thread t1 = new ThreadPrioritiesDemo("thread1", 1);
Thread t2 = new ThreadPrioritiesDemo("thread2", 10);
t1.start();
t2.start();
}
@Override
public void run() {
Thread.currentThread().setPriority(priority);
for (int i = 0; i < 1000; i++) {
System.out.println(this + ":" + i);
if (i % 2 == 0)
Thread.yield();
}
}
}
输出结果(截取部分):
Thread[thread1,1,main]:670
Thread[thread2,10,main]:293
Thread[thread2,10,main]:294
Thread[thread1,1,main]:671
Thread[thread1,1,main]:672
Thread[thread2,10,main]:295
Thread[thread2,10,main]:296
Thread[thread1,1,main]:673
Thread[thread1,1,main]:674
Thread[thread2,10,main]:297
Thread[thread2,10,main]:298
Thread[thread1,1,main]:675
Thread[thread1,1,main]:676
Thread[thread2,10,main]:299
3.1、结果说明
新开启2个线程,线程1优先级为1,线程2优先级为10,两个线程交替执行,高优先级线程(t2)并不是一直优先于t1执行
四、总结
高优先级线程并不是一直优于低优先级线程执行
转载请注明作者及出处,并附上链接http://www.jianshu.com/u/ada8c4ee308b
网友评论