java提供一个线程调度器监控程序中启动后进入就绪状态的所有线程,调度器按照优先级决定线程执行顺序。(优先级只表示获得调度的概率,并不是优先级低的不被调用,最终还是取决于CPU的调度)
优先级用数字表示,1~10,默认为5。
通过get.Priority(),setPriority()获取和设置优先级。
public class Priority implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority()); } public static void main(String[] args) { System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority()); Priority p = new Priority(); Thread a = new Thread(p); Thread b = new Thread(p); Thread c = new Thread(p); Thread d = new Thread(p); Thread e = new Thread(p); Thread f = new Thread(p); a.setPriority(Thread.MIN_PRIORITY); a.start(); b.setPriority(7); b.start(); c.setPriority(Thread.MAX_PRIORITY); c.start(); d.setPriority(2); d.start(); e.setPriority(Thread.NORM_PRIORITY); e.start(); f.setPriority(9); f.start(); } }
main-->5 Thread-2-->10 Thread-5-->9 Thread-1-->7 Thread-4-->5 Thread-3-->2 Thread-0-->1