线程的优先级
Thread类提供了setPriority(int newPriority) 和 getPriority()方法来设置和获取一个线程的优先级,其中setPriority方法的参数是 [1-10] 之间的整数,值越大,优先级越高。
在Thread类中也定义了三个优先级常量:
public final static int MIN_PRIORITY = 1;
public final static int NORM_PRIORITY = 5;
public final static int MAX_PRIORITY = 10;
线程的优先级并不会保证线程的执行顺序,只影响线程获取CPU资源的概率大小。
public class PriorityTest {
static class MyThread extends Thread {
@Override
public void run() {
//起始时间
long start = System.currentTimeMillis();
long result = 0;
//获取1000个0-100的随机数累加和
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 10; j++) {
result += getValue(j);
}
}
//终止时间
long end = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName() + ",priority:" +
super.getPriority() + ",耗费的时间:"+ (end - start) +
"毫秒.result=" + result);
}
//获取0-100的随机数
private long getValue(int j) {
return (long) (j * Math.random() * 10);
}
}
public static void main(String[] args) {
//创建线程数组
Thread[] threads = new Thread[10];
//循环创建线程对象
for (int i = 0; i < threads.length; i++) {
threads[i] = new MyThread();
if (i < 5) {
//设置最小优先级
threads[i].setPriority(Thread.MIN_PRIORITY);
} else {
//设置最小优先级
threads[i].setPriority(Thread.MAX_PRIORITY);
}
}
// 启动所有线程
for (Thread t : threads) {
t.start();
}
}
}
一般情况下,高优先级线程更早执行完毕。
优先级高的线程获得CPU的机会更多一些,但是不一定高优先级的线程先执行完毕。多线程有随机性的特点,仅通过优先级是无法保证多线程的执行顺序的。
线程优先级具有继承性,A线程中启动了B线程,也没有设置B线程的优先级,B线程的优先级默认和A相同。
public class PriorityTest2 {
static class MyThread extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + ",priority:" + Thread.currentThread().getPriority());
new MyThread2().start();
}
}
static class MyThread2 extends Thread {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() +
",priority:" + Thread.currentThread().getPriority());
}
}
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName() + ",priority:"
+ Thread.currentThread().getPriority());
MyThread t = new MyThread();
t.setPriority(Thread.MAX_PRIORITY);
t.start();
}
}