Java线程的优先级

主要方法:设置优先级public final void setPriority(int newPriority)、取得优先级public final int getPriority()

public class TestThread3 {
public void code1(){

    //1.主线程的优先级,中等优先级5
    // System.out.println("主线程的优先级"+Thread.currentThread().getPriority());

    //2.在主线程中创建一个线程,未指定优先级 lamda表达式
    Thread threadA =new Thread(()->{
        System.out.println(Thread.currentThread().getName()
                +"优先级:"+Thread.currentThread()
                .getPriority());
    },"Thread-A");
    threadA.start();
    threadA.setPriority(6);
}

    public static void main(String[] args) {


    Runnable runnable=new PriorityRunnable();
    Thread threadA =new Thread(runnable,"Thread-A");
    threadA.setPriority(Thread.MAX_PRIORITY);//10
    Thread threadB =new Thread(runnable,"Thread-B");
    threadB.setPriority(Thread.MIN_PRIORITY);//5
    Thread threadC =new Thread(runnable,"Thread-C");
    threadC.setPriority(Thread.NORM_PRIORITY);//1
    threadA.start();
    threadB.start();
    threadC.start();
   }
}
class PriorityRunnable implements Runnable{

    @Override
    public void run() {
        Thread t=Thread .currentThread();
        System.out.println(t.getName()+"优先级"+t.getPriority());
    }
}

线程是有继承关系的,比如当A线程中启动B线程,那么B和A的优先级将是一样的

    public static void main(String[] args) {
        //本来main优先级是5
        System.out.println(Thread.currentThread().getName() + "," + Thread.currentThread().getPriority());
        //main中启动A,设置优先级为10,则它的子和孙也是10
        Thread thread = new Thread(new A(), "子线程A");
        thread.setPriority(Thread.MAX_PRIORITY);
        thread.start();
    }
class A implements Runnable {
    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "," + Thread.currentThread().getPriority());
    //A中启动B
        new Thread(new B()).start();
    }
}

class B implements Runnable {
    @Override
    public void run() {
        System.out.println("孙子的优先级:" + Thread.currentThread().getPriority());
    }
main,5
子线程A,10
孙子的优先级:10
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值