1.线程的优先级(鸡肋)
Java线程可以有优先级的设定,高优先级的线程比低优先级的线程有更高的几率得到执行。但也只是执行几率大,不是一定会先执行,由调度程序决定哪一个线程被执行,线程的优先级是高度依赖于系统的。
- 优先级可以用从1到10的范围指定。10表示最高优先级,1表示最低优先级,5是普通优先级(在源码里注释的是默认优先级)。
- 你可以使用常量,如MIN_PRIORITY,MAX_PRIORITY,NORM_PRIORITY来设定优先级。
附上jdk源码里线程优先级值的部分
代码示例:
package com.thread;
class MyThread1 implements Runnable{
@Override
public void run() {
for (int i = 0; i <100; i++) {
System.out.println(Thread.currentThread().getName()+"___***__"+i);
}
}
}
class MyThread2 implements Runnable{
@Override
public void run() {
for (int i = 0; i <100; i++) {
System.out.println(Thread.currentThread().getName()+"__###___"+i);
}
}
}
public class ThreadPriority {
public static void main(String[]args) {
MyThread1 th1=new MyThread1();
MyThread2 th2=new MyThread2();
Thread t1=new Thread(th1);
Thread t2=new Thread(th2);
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}
输出结果:
注意:
不要假定高优先级的线程一定先于低优先级的线程执行,不要有逻辑依赖于线程优先级,否则可能产生意外结果。