31 多线程(四)——线程优先级

优先级概念

  • 线程的优先级可以让线程获得高概率或低概率的cpu调度机会。不是绝对的优先,只是高优先级会被优先调用。
  • 优先级为1-10,最低为1,最高为10,默认为5。可以自行设置值。
  • 设置优先级必需在线程start()之前。
  • Thread类的优先级常量
    • MAX_PRIORITY        10
    • MIN_PRIORITY         1
    • NORM_PRIORITY     5  默认优先级

演示

/**
 * 线程优先级
 * @author UID
 *
 */
public class Demo04_PRIORITY {
	public static void main(String[] args) {
		F f = new F();
		Thread t1 = new Thread(f,"线程1");
		Thread t2 = new Thread(f,"线程2");
		Thread t3 = new Thread(f,"线程3");
		t1.setPriority(Thread.MAX_PRIORITY);//设置为最大优先级
		t3.setPriority(Thread.MIN_PRIORITY);
		t2.setPriority(3);//自定义优先级
		t1.start();
		t2.start();
		t3.start();
		
	}
}

class F extends Thread{
	@Override
	public void run() {
		for (int i = 0; i < 50; i++) {
			System.out.println(Thread.currentThread().getName()+"-->"+i);
		}
	}
}

  

原文地址:https://www.cnblogs.com/Scorpicat/p/11983799.html