Java线程的优先级

万事离不开方法,世界离不开秩序。Java线程的执行也是有一个顺序的,也就是优先级。CPU会根据线程的优先级合理分配资源而不会产生冲突。
线程的优先级
在java语言中,线程优先级一共有10级,优先级较高的线程会被优先执行,当执行完毕,才会轮到优先级较低的线程执行。如果优先级相同,那么就按照提交顺序(也就是代码编写顺序)执行的方式。
在这里插入图片描述
优先级的使用

设置优先级的方法:setPriority(int newPriority)

获取优先级的方法:getPriority()

线程优先级的特点

  1. 线程优先级的继承特性:也就是如果线程A启动线程B,那么线程A和B的优先级是一样的;
  2. 线程优先级的规则性:即线程会优先级的大小顺序执行,但是不一定是优先级较大的先执行完,因为线程的优先级还有下面第三个特性:
  3. 线程优先级的随机特性;

接下来我们来看一个例子:

public class TheadPri {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		for(int i=1;i<=10;i++){
		thread1 th1 =new thread1("+","4");
		th1.setPriority(4);
		thread1 th2 =new thread1("-","6");
		th2.setPriority(6);
		thread3 th3 =new thread3("÷","10");
		/*可以这样设置线程优先级别为10
		 * th3.setPriority(10);
		 * 还可以用下面的方法操作
		 */
		th3.setPriority(Thread.MAX_PRIORITY);	
		th1.start();
		th2.start();
		th3.start();
		}
	}
}
class thread1 extends Thread{
	String name;
	String Priority;
	thread1(String name,String Priority){
		this.name=name;
		this.Priority=Priority;
	}
	public void run() {
		// TODO Auto-generated method stub
	System.out.println(name+"优先级是"+Priority);
	}
}

class thread2 extends Thread{
	String name;
	String Priority;
	thread2(String name,String Priority){
		this.name=name;
		this.Priority=Priority;
	}
	public void run() {
		// TODO Auto-generated method stub
	System.out.println(name+"优先级是"+Priority);
	}
}

class thread3 extends Thread{
	String name;
	String Priority;
	thread3(String name,String Priority){
		this.name=name;
		this.Priority=Priority;
	}
	public void run() {
		// TODO Auto-generated method stub
	System.out.println(name+"优先级是"+Priority);
	}
}


代码多次运行之后会发现,大部分情况下运行结果满足线程的特点2,线程3都是先执行完,线程2第二执行完,线程1最后执行完(注意这里执行完不是线程1要等线程2和线程3执行完后再执行)
还有就是线程优先级的随机性,所以线程有时候并不是按照预先设置好的优先级执行。

参考文献1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值