线程优先级

线程优先级:

Java线程可以有优先级的设定,高优先级的线程比低优先级的线程有更高的几率得到执行

  1. 线程的优先级没有指定时,所有线程都携带普通优先级。
  2. 优先级可以用从1到10的范围指定。10表示最高优先级,1表示最低优先级,5是普通优先级。
  3. 优先级最高的线程在执行时被给予优先。但是不能保证线程在启动时就进入运行状态。
  4. 与在线程池中等待运行机会的线程相比,当前正在运行的线程可能总是拥有更高的优先级。
  5. 调度程序决定哪一个线程被执行。
  6. t.setPriority()用来设定线程的优先级。
  7. 记住在线程开始方法被调用之前,线程的优先级应该被设定。
  8. 你可以使用常量,如MIN_PRIORITY,MAX_PRIORITY,NORM_PRIORITY来设定优先

例子:

 1 public static void main(String[] args) {
 2         // TODO Auto-generated method stub
 3         Thread t1 =new Thread(){
 4             public void run(){
 5                 for(int i=0; i<100; i++){
 6                     System.out.println("aaa");
 7                 }
 8             }
 9         };
10         
11         Thread t2 =new Thread(){
12             public void run(){
13                 for(int i=0; i<100; i++){
14                     System.out.println("bbb");
15                 }
16             }
17         };
18         
19         t1.setPriority(Thread.MAX_PRIORITY);
20         t2.setPriority(Thread.MIN_PRIORITY);
21         
22         t1.start();
23         t2.start();
24     }
原文地址:https://www.cnblogs.com/feichangnice/p/10648794.html