在 Java 中更改线程优先级


可以通过实现 Runnable 接口并重写 run() 方法来创建一个线程。然后可以创建一个 Thread 对象并调用 start() 方法。

线程优先级决定了将处理器提供给线程以及其他资源的时间。可以使用 Thread 类的 setPriority() 方法来更改它。

以下给出了一个程序,演示如何在 Java 中使用 setPriority() 方法更改线程优先级

示例

 在线演示

public class ThreadDemo extends Thread {
   public void run() {
      System.out.println("Running...");
   }
   public static void main(String[] args) {
      ThreadDemo thread1 = new ThreadDemo();
      ThreadDemo thread2 = new ThreadDemo();
      ThreadDemo thread3 = new ThreadDemo();
      ThreadDemo thread4 = new ThreadDemo();
      ThreadDemo thread5 = new ThreadDemo();
      System.out.println("Default thread priority of Thread 1: " + thread1.getPriority());
      System.out.println("Default thread priority of Thread 2: " + thread2.getPriority());
      System.out.println("Default thread priority of Thread 3: " + thread3.getPriority());
      System.out.println("Default thread priority of Thread 4: " + thread4.getPriority());
      System.out.println("Default thread priority of Thread 5: " + thread5.getPriority());
      System.out.println("
Changing the default thread priority using the setPriority() method");       thread1.setPriority(7);       thread2.setPriority(3);       thread3.setPriority(9);       thread4.setPriority(2);       thread5.setPriority(8);       System.out.println("
Changed thread priority of Thread 1: " + thread1.getPriority());       System.out.println("Changed thread priority of Thread 2: " + thread2.getPriority());       System.out.println("Changed thread priority of Thread 3: " + thread3.getPriority());       System.out.println("Changed thread priority of Thread 4: " + thread4.getPriority());       System.out.println("Changed thread priority of Thread 5: " + thread5.getPriority());       System.out.println("
" + Thread.currentThread().getName());       System.out.println("
Default thread priority of Main Thread: " + Thread.currentThread().getPriority());       Thread.currentThread().setPriority(10);       System.out.println("Changed thread priority of Main Thread: " + Thread.currentThread().getPriority());    } }

输出

Default thread priority of Thread 1: 5
Default thread priority of Thread 2: 5
Default thread priority of Thread 3: 5
Default thread priority of Thread 4: 5
Default thread priority of Thread 5: 5
Changing the default thread priority using the setPriority() method
Changed thread priority of Thread 1: 7
Changed thread priority of Thread 2: 3
Changed thread priority of Thread 3: 9
Changed thread priority of Thread 4: 2
Changed thread priority of Thread 5: 8
main
Default thread priority of Main Thread: 5
Changed thread priority of Main Thread: 10

更新日期:2019 年 7 月 30 日

610 次观看

开启你的 职业生涯

完成课程后获得认证

开始
广告
© . All rights reserved.