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();
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值