在 Java 中的线程可以拥有自己的优先级,优先级高的线程在竞争资源时会更有优势,更能抢到资源,但并不能保证一定能抢到资源。线程的优先级调度和底层操作系统有密切关系,在各个平台上表现不一。并且优先级产生的后果也不容易预测,可能会产生饥饿。所以在要求严格的场合,还是需要自己在应用层解决程序调度问题。
package com.demo.base;public class ThreadDemo {public static void main(String[] args) {Thread t1 = new Thread(new MyRunnable(), "T1");Thread t2 = new Thread(new MyRunnable(), "T2");// 设置线程优先级t1.setPriority(Thread.MAX_PRIORITY);t2.setPriority(Thread.MIN_PRIORITY);t1.start();t2.start();}}class MyRunnable implements Runnable {@Overridepublic void run() {String name = Thread.currentThread().getName();System.out.println("线程: " + name + " 开始执行。。。");int i = 0;while (true){System.out.println("线程: " + name + "---" + i);synchronized (this) {i++;if(i > 1000000){break;}}}}}
注意:
- 线程的优先级是用 1 到 10 的数字表示,数字越大则优先级越高
- 在 Thread 类中内置了三个静态常量用作常用的线程优先级
public final static int MIN_PRIORITY = 1;
public final static int _NORM_PRIORITY = 5;
public final static int _MAX_PRIORITY = 10;
