多线程优先级——Priority

博客探讨了Java中线程的优先级设置,虽然10是最高优先级,但并不保证优先级高的线程一定先执行。示例代码创建了不同优先级的线程,结果显示即使优先级低的线程也可能先于高优先级线程运行,说明线程执行的顺序依赖于操作系统调度,并非优先级决定绝对顺序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

线程的优先级1-10

  • 1.NORM_PRIORITY 5 默认
  • 2.MIN_PRIORITY 1
  • 3.MAX_PRIORITY 10
  • 概率,不代表绝对的先后顺序,也就是说优先级为10的并不一定就比优先级为1的先运行,只是它先运行的概率比优先级为1的大,优先级为1-10,不能超过这个范围。
  • 一般默认优先级为5.
package thread.lzy.www;
/**
 * 线程的优先级1-10
 * 1.NORM_PRIORITY 5 默认
 * 2.MIN_PRIORITY 1
 * 3.MAX_PRIORITY
 * 概率,不代表绝对的先后顺序
 * @author Administration
 *
 */
public class eProrityTest {

	public static void main(String[] args) {
		System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
		 MyPriority mp=new  MyPriority();
		Thread t1=new Thread(mp,"a");
		Thread t2=new Thread(mp,"b");
		Thread t3=new Thread(mp,"c");
		Thread t4=new Thread(mp,"d");
		Thread t5=new Thread(mp,"e");
		Thread t6=new Thread(mp,"f");
		//设置优先级在启动前
		t1.setPriority(Thread.MAX_PRIORITY);//t1.setPriority(10);也可以直接写数字1-10都可
		t2.setPriority(Thread.MAX_PRIORITY);
		t3.setPriority(Thread.MAX_PRIORITY);
		t4.setPriority(Thread.MIN_PRIORITY);
		t5.setPriority(Thread.MIN_PRIORITY);
		t6.setPriority(Thread.MIN_PRIORITY);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
		t6.start();
		 
	}
}
class MyPriority implements Runnable{

	@Override
	public void run() {
		
		System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
	}
	
}

代码中a,b,c的优先级为10。d,e,f的优先级为1,但真的就是a,b,c先运行吗 ,答案不是的,
某次运行结果:
main–>5
a–>10
b–>10
e–>1
c–>10
d–>1
f–>1
可以看出c虽然优先级高于e,但并没有先运行,只是它的概率高而已

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值