Java基础---线程的优先级

线程的优先级

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();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值