Java并发编程入门 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

线程的优先级

在操作系统中,线程存在优先级关系,具有高优先级的线程会获得更多CPU的资源,优先级低的线程会获得少的CPU资源呢。在Java虚拟机中,线程的优先级也是如此。在Java中,线程分为10个优先级。下面我们先了解一下线程优先级的性质。

1.线程的优先级具有继承性:即一个类被继承之后优先级也会被继承。

2.线程的优先级具有规则性:高优先级的线程总是大部分情况下先执行完。

3.线程优先级具有不确定性:虽然CPU的资源分配的多了,但是线程在执行的时候并不是按照一定计划执行的,所以执行结果往往是不确定的。

如何设置线程的优先级?

Java中使用public final void setPriority(int newPriority)来设置线程的优先级。

下面是一段实例:

public class Main {
    public static void main(String[] args){
        TestThread test=new TestThread();
        test.setPriority(10);
    }
    public static class TestThread extends Thread{
        public void run(){
            System.out.println("Hello world");
        }
    }
}

这段代码吧test实例的线程设置为10

试着写两个线程,设置优先级,观察运行结果。下面是例子: public class Main { public static void main(String[] args){ TestThread test=new TestThread(); TestThread test2=new TestThread(); test.setPriority(10); test2.setPriority(6); test.start(); test2.start(); } public static class TestThread extends Thread{ public void run(){ for(int i=0;i<50;i++){ System.out.println(Thread.currentThread().getId()+":"+i); } } } }