Bootstrap

Java学习,查看线程优先级

Java 每个线程都有一个与之关联的优先级,它决定了线程相对于其他线程被调度的机会。Java 提供了三个常量,表示线程的优先级:Thread.MIN_PRIORITY(1)、Thread.NORM_PRIORITY(5)和 Thread.MAX_PRIORITY(10)。查看线程的优先级,可以通过访问线程的 getPriority() 方法。

线程的优先级,示例:

public class ThreadPriorityExample { 
    public static void main(String[] args) {
        // 创建线程
        Thread thread1 = new Thread(new RunnableTask(), "Thread-1");
        
        // 设置线程的优先级
        thread1.setPriority(Thread.MIN_PRIORITY);
        
        // 启动线程
        thread1.start();
 
        // 主线程和新线程的优先级
        printThreadPriority("Main Thread", Thread.currentThread());
        printThreadPriority("Thread-1", thread1);
    }
 
    // 定义一个任务
    static class RunnableTask implements Runnable {
        @Override
        public void run() {
            // 查看和打印优先级
            printThreadPriority(Thread.currentThread().getName(), Thread.currentThread());
        }
    }
 
    // 打印线程名称和优先级
    static void printThreadPriority(String threadName, Thread thread) {
        System.out.println("Thread Name: " + threadName + ", Priority: " + thread.getPriority());
    }
}

输出结果:

Thread Name: Main Thread, Priority: 5
Thread Name: Thread-1, Priority: 1
Thread Name: Thread-1, Priority: 1

 

;