天天看点

Java多线程调度—优先级

一. 线程的调度-优先级

与线程休眠类似,线程的优先级仍然无法保障线程的执行次序。只不过,优先级高的线程获取CPU资源的概率较大,优先级低的并非没机会执行(优先级低的也可能会被执行)。线程的优先级用1-10之间的整数表示,数值越大优先级越高,默认的优先级为5。

设置线程的优先级:线程默认的优先级是创建它的执行线程的优先级。可以通过setPriority(int newPriority)更改线程的优先级。例如:

        Thread t = new MyThread();

        t.setPriority(8);

        t.start();

线程默认优先级是5,Thread类中有三个常量,定义线程优先级范围:

static int MAX_PRIORITY

          线程可以具有的最高优先级。

static int MIN_PRIORITY

          线程可以具有的最低优先级。

static int NORM_PRIORITY

          分配给线程的默认优先级。

二. 例子

public class PriorityTest implements Runnable {

	@Override
	public void run() {
		for (int i = 1; i <= 10; i++) {

			System.out.println(Thread.currentThread().getName() + "........."
					+ i);
		}
	}

	public static void main(String[] args) {
		Thread tall = new Thread(new PriorityTest(), "张三");
		Thread low = new Thread(new PriorityTest(), "李四");

		tall.setPriority(10);
		low.setPriority(1);

		tall.start();
		low.start();
	}
}
           

继续阅读