演示Java中的线程优先级

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

线程优先级可以由JVM或程序员提供给线程。它确定何时向线程提供处理器以及其他资源。setPriority()Thread类的方法可用于设置线程的优先级。

给出了一个演示Java线程优先级的程序,如下所示:

示例

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());

      thread1.setPriority(8);

      thread2.setPriority(1);

      thread3.setPriority(6);

      thread4.setPriority(9);

      thread5.setPriority(3);

      System.out.println("Modified thread priority of Thread 1: " + thread1.getPriority());

      System.out.println("Modified thread priority of Thread 2: " + thread2.getPriority());

      System.out.println("Modified thread priority of Thread 3: " + thread3.getPriority());

      System.out.println("Modified thread priority of Thread 4: " + thread4.getPriority());

      System.out.println("Modified thread priority of Thread 5: " + thread5.getPriority());

      System.out.print(Thread.currentThread().getName());

      System.out.println("\nDefault thread priority of Main Thread: " + Thread.currentThread().getPriority());

      Thread.currentThread().setPriority(10);

      System.out.println("Modified 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

Modified thread priority of Thread 1: 8

Modified thread priority of Thread 2: 1

Modified thread priority of Thread 3: 6

Modified thread priority of Thread 4: 9

Modified thread priority of Thread 5: 3

main

Default thread priority of Main Thread: 5

Modified thread priority of Main Thread: 10

以上是 演示Java中的线程优先级 的全部内容, 来源链接: utcz.com/z/316667.html

回到顶部