美文网首页
6、线程的优先级

6、线程的优先级

作者: 金石_832e | 来源:发表于2021-12-14 09:54 被阅读0次

    线程优先级分为10个等级,主线程优先级不变,优先级越高代表执行的顺序越靠前,但不排除出现优先级低的线程先运行。
    线程若想设置优先级,必须先设置再启动!!!

    package com.example.demo.thread;
    
    /**
     * @projectName: demo
     * @package: com.example.demo.thread
     * @className: TestPriority
     * @author: 
     * @description: 测试线程的优先级
     * @date: 2021/12/7 22:06
     */
    public class TestPriority {
        public static void main(String[] args) {
            System.out.println(Thread.currentThread().getName()+":------------------>"+Thread.currentThread().getPriority());
    
            MyPriority myPriority = new MyPriority();
            Thread t1 = new Thread(myPriority,"t1");
            Thread t2 = new Thread(myPriority,"t2");
            Thread t3 = new Thread(myPriority,"t3");
            Thread t4 = new Thread(myPriority,"t4");
            Thread t5 = new Thread(myPriority,"t5");
    
            t1.setPriority(Thread.MIN_PRIORITY);
            t2.setPriority(Thread.MAX_PRIORITY);
            t3.setPriority(Thread.NORM_PRIORITY);
            t4.setPriority(7);
            t5.setPriority(3);
    
            t1.start();
            t2.start();
            t3.start();
            t4.start();
            t5.start();
    
        }
    }
    class MyPriority implements Runnable{
    
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName()+":------------------>"+Thread.currentThread().getPriority());
        }
    }
    
    第一次执行
    第二次执行
    第N次执行

    相关文章

      网友评论

          本文标题:6、线程的优先级

          本文链接:https://www.haomeiwen.com/subject/csxzxrtx.html