Java 线程优先级

197 阅读1分钟

内容

获取优先级getPriority()和设置优先级setPriority(int a);优先级只能设置1到10,不设置默认为5
优先级高也不一定先执行,看cpu心情,优先级高只能说先执行的概率变高

用例

public class ThreadPriority {
    public static void main(String[] args) {
        //输出main线程优先级
        System.out.println(Thread.currentThread().getName()+"------"+Thread.currentThread().getPriority());
        T t = new T();
        Thread tt0 = new Thread(t);
        Thread tt1 = new Thread(t);
        Thread tt2 = new Thread(t);
        Thread tt3 = new Thread(t);
        Thread tt4 = new Thread(t);
        Thread tt5 = new Thread(()->{try {//让优先级为10的线程5多延迟些
            Thread.sleep(9000);
            System.out.println(Thread.currentThread().getName()+"------"+Thread.currentThread().getPriority());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }});
        tt0.start();
        tt1.setPriority(Thread.MIN_PRIORITY);//1
        tt2.setPriority(6);
        tt3.setPriority(Thread.NORM_PRIORITY);//5
        tt4.setPriority(9);
        tt5.setPriority(Thread.MAX_PRIORITY);//10
        tt1.start();
        tt2.start();
        tt3.start();
        tt4.start();
        tt5.start();



    }
}
class T implements Runnable{
    @Override
    public void run() {
        try {
            Thread.sleep(4000);
            System.out.println(Thread.currentThread().getName()+"------"+Thread.currentThread().getPriority());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}