温馨提示×

java线程优先级怎么设置

小亿
78
2023-11-07 04:27:55
栏目: 编程语言

在Java中,线程优先级可以通过setPriority()方法来设置。优先级是一个整数值,范围从1到10,其中1是最低优先级,10是最高优先级。默认情况下,所有线程都具有相同的优先级,即5。

下面是一个示例代码,演示如何设置线程的优先级:

public class ThreadPriorityExample {
    public static void main(String[] args) {
        Thread thread1 = new MyThread("Thread 1");
        Thread thread2 = new MyThread("Thread 2");
        
        thread1.setPriority(8);
        thread2.setPriority(3);
        
        thread1.start();
        thread2.start();
    }
}

class MyThread extends Thread {
    public MyThread(String name) {
        super(name);
    }
    
    @Override
    public void run() {
        System.out.println(getName() + " is running.");
    }
}

在上面的示例中,我们创建了两个线程thread1thread2,然后分别使用setPriority()方法设置它们的优先级为8和3。然后,我们启动这两个线程。根据线程优先级的设置,高优先级的线程可能会更频繁地执行,但并不能保证一定会这样。

0