美文网首页
多线程常用方法3(线程优先级)

多线程常用方法3(线程优先级)

作者: 秋笙fine | 来源:发表于2019-01-24 17:18 被阅读0次

所谓的优先级指的是越高的优先级,越有可能先执行。

主要又以下两步:
1.设置优先级 public final void setPriority(int newPriority)
2.取得优先级 public final int getPriority()

我们发现设置和取得优先级都使用了int数据类型。对于这种情况,有三种取值。
最高优先级:public static final int MAX_PRIORITY

中等优先级:public static final int NORM_PRIORITY

最低优先级:public static final int MIN_PRIORITY

范例:测试优先级:

package TestDemo;



class MyThread implements Runnable{//Runnable接口子类,也是线程公有对象,其实例化对象在堆中
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+",x="+i);
        }
    }   
}

public class TestDemo{
    
    public static void main(String[] args)throws Exception{
        MyThread mt=new MyThread();
    
        Thread thread1=new Thread(mt,"Thread A");
        Thread thread2=new Thread(mt,"Thread B");
        Thread thread3=new Thread(mt,"Thread C");

        thread3.setPriority(Thread.MAX_PRIORITY);
        thread2.setPriority(Thread.MIN_PRIORITY);
        thread1.setPriority(Thread.MIN_PRIORITY);

        thread1.start();
        thread2.start();
        thread3.start();

    }
    
}

结果:


image.png

因为有可能,所以线程优先级不那么明显

相关文章

网友评论

      本文标题:多线程常用方法3(线程优先级)

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