192°

3.线程优先级

多线程优先级:

多线程优先级为1~10,数字越大,优先级越高。

一个线程不设置优先级的话,默认优先级为5;

/**
     * The minimum priority that a thread can have.
     */
public final static int MIN_PRIORITY = 1;

/**
     * The default priority that is assigned to a thread.
     */
public final static int NORM_PRIORITY = 5;

/**
     * The maximum priority that a thread can have.
     */
public final static int MAX_PRIORITY = 10;

以上,是Thread类提供的三个优先级常量。

设置优先级的方法为,Thread对象或继承了Thread类的对象,调用setPriority( )方法。

实例:

package com.xm.thread.t_19_01_26;

import java.util.concurrent.TimeUnit;

public class PriorityThread {

    public static void main(String[] args) throws InterruptedException {
        HightPriorityThread hightPriorityThread = new HightPriorityThread();
        LowPriorityThread lowPriorityThread = new LowPriorityThread();

        hightPriorityThread.setPriority(Thread.MAX_PRIORITY);
        lowPriorityThread.setPriority(Thread.MIN_PRIORITY);

        lowPriorityThread.start();
        hightPriorityThread.start();

        TimeUnit.SECONDS.sleep(1);

        System.out.println("默认优先级别!");
    }

}

class HightPriorityThread extends Thread{

    @Override
    public void run() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("优先级别高!");
    }
}

class LowPriorityThread extends Thread{

    @Override
    public void run() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("优先级别低!");
    }
}

运行结果:

第1次运行结果:

优先级别高!

默认优先级别!

优先级别低!

第2次运行结果:

默认优先级别!

优先级别高!

优先级别低!

结果分析:

虽然优先级别可以设置,但通过以上运行结果我们可以看出,它并不能真正控制线程在CPU上的调度顺序。

原文链接:https://www.cnblogs.com/TimerHotel/p/thread03.html

全部评论: 0

    我有话说: