java 设置线程优先级

线程优先级使用

1.1 不设置优先级

class PriorityThread extends Thread{
    @Override
    public void run(){
        for(int i = 0;i < 5;i++){
            System.out.println(Thread.currentThread().getName() + "---" + i);
        }
    }
}
public class Demo {
    public static void main(String[] args) {
        PriorityThread priorityThread1 = new PriorityThread();
        priorityThread1.setName("线程1");
        PriorityThread priorityThread2 = new PriorityThread();
        priorityThread2.setName("线程2");
        PriorityThread priorityThread3 = new PriorityThread();
        priorityThread3.setName("线程3");

        priorityThread1.start();
        priorityThread2.start();
        priorityThread3.start();
    }
}
输出结果:
线程2---0
线程1---0
线程3---0
线程1---1
线程2---1
线程1---2
线程3---1
线程1---3
线程3---2
线程1---4
线程2---2
线程3---3
线程2---3
线程2---4
线程3---4

1.2 设置优先级

class PriorityThread extends Thread{
    @Override
    public void run(){
        for(int i = 0;i < 5;i++){
            System.out.println(Thread.currentThread().getName() + "---" + i);
        }
    }
}
public class Demo {
    public static void main(String[] args) {
        PriorityThread priorityThread1 = new PriorityThread();
        priorityThread1.setName("线程1");
        priorityThread1.setPriority(Thread.MAX_PRIORITY); // 设置最大优先级
        PriorityThread priorityThread2 = new PriorityThread();
        priorityThread2.setName("线程2");
        priorityThread2.setPriority(Thread.NORM_PRIORITY);
        PriorityThread priorityThread3 = new PriorityThread();
        priorityThread3.setName("线程3");
        priorityThread3.setPriority(Thread.MIN_PRIORITY);

        priorityThread1.start();
        priorityThread2.start();
        priorityThread3.start();
    }
}
输出结果:
线程2---0
线程1---0
线程3---0
线程1---1
线程2---1
线程1---2
线程3---1
线程1---3
线程2---2
线程3---2
线程2---3
线程1---4
线程2---4
线程3---3
线程3---4

1.3 总结

  • 在Java中,线程优先级(Thread Priority)提供了一种机制,用于提示线程调度器(Thread Scheduler)哪一个线程更重要或者应该得到更多的CPU时间。然而,线程优先级并不保证一定会影响线程的调度顺序。其影响程度取决于底层操作系统的线程调度算法和JVM实现。

  • 不建议过度依赖线程优先级来控制线程调度。更好的方法是使用同步和并发工具(如锁、条件、信号量、线程池等)来协调线程的执行顺序和资源共享。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值