IT干货网

线程的优先级

luoye 2022年03月12日 编程设计 190 0

线程的优先级

java可以查看和设置线程的优先级,优先级用数字表示,越大表示优先级越高,范围为整数1到10。

以下代码演示如何查看和设置优先级:

package com.cxf.multithread.priority; 
 
public class TestForPriority implements Runnable{ 
    @Override 
    public void run() { 
        System.out.println(Thread.currentThread().getName()+" priority is "+Thread.currentThread().getPriority()); 
    } 
 
    public static void main(String[] args) { 
        Thread thread1 = new Thread(new TestForPriority()); 
        Thread thread2 = new Thread(new TestForPriority()); 
        Thread thread3 = new Thread(new TestForPriority()); 
 
        thread1.setPriority(4); 
        thread2.setPriority(9); 
        thread3.setPriority(10); 
 
        System.out.println("main priority is "+Thread.currentThread().getPriority()); 
 
        thread1.start(); 
        thread2.start(); 
        thread3.start(); 
    } 
} 
 

输出结果:

main priority is 5 
Thread-0 priority is 4 
Thread-1 priority is 9 
Thread-2 priority is 10 

setPriority方法设置优先级,getPriority方法查看优先级。

小规模的任务从运行结果体现不出来线程优先级。


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!