iteye_5468 2011-05-12 17:28
浏览 343
已采纳

java多线程的setPriority设置线程优先级

这是java线程的优先级:
java.lang.Thread
public static final int MAX_PRIORITY 10
public static final int MIN_PRIORITY 1
public static final int NORM_PRIORITY 5

默认main方法也就是主线程的级别是5,这个我测试过啦:


public static void main(String args []){
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader);
System.out.println(Thread.currentThread().getPriority());
System.out.println(Thread.currentThread().getName());
}


打印输出的结果是5和main

现在我自己创建5个线程,并分别给每个线程设置最小线程优先级:

public class Test extends Thread{
private int countDown = 5;
  private int threadNumber;
  private static int threadCount = 0;
  public Test() {
    threadNumber = ++threadCount;
    System.out.println("Making " + threadNumber);
  }
  public void run() {
    while(true) {
      System.out.println("Thread " + 
        threadNumber + "(" + countDown + ")");
      if(--countDown == 0) return;
    }
  }


public static  void main(String args []){
    for(int i = 0; i < 5; i++){
          Test  test = new Test();
          System.out.println("Test"+(i+1)+":"+test.getName());
          test.setPriority(1);   //设置为最小级别
          System.out.println("Test"+(i+1)+":"+test.getPriority());
          test.start();
    }
    System.out.println("All Threads Started");
    System.out.println(Thread.currentThread().getPriority());
    System.out.println(Thread.currentThread().getName());
}

}


按照上面这个代码,我给每个自定义的线程设置优先级为1,应该是等主线程,MAIN执行完之后才执行另外5个自定义线程。
也就是先要打印构造函数里面的值,才开始执行run,但是为什么输出的结果是一下这个样子:
Making 1
Test1:Thread-1
Test1:1
Making 2
Test2:Thread-2
Test2:1
Making 3
Test3:Thread-3
Thread 2(5)
Thread 1(5)
Thread 2(4)
Test3:1
Thread 1(4)
Thread 2(3)
Thread 2(2)
Thread 2(1)
Making 4
Test4:Thread-4
Test4:1
Thread 1(3)
Thread 3(5)
Thread 4(5)
Making 5
Thread 3(4)
Thread 1(2)
Thread 4(4)
Test5:Thread-5
Thread 3(3)
Thread 1(1)
Thread 4(3)
Test5:1
Thread 3(2)
Thread 4(2)
Thread 3(1)
Thread 4(1)
All Threads Started
Thread 5(5)
5
Thread 5(4)
main
Thread 5(3)
Thread 5(2)
Thread 5(1)

是不是我对优先级理解错误啦。寻求真相。
问题补充
fmjsjx 写道
所谓线程优先级,个人理解只是对资源竞争的一个辨别依据,就是说当多个线程竞争资源时,具有较高优先级的线程会优先执行。
楼主的线程执行过程太短、逻辑太简单,基本不存在竞争问题,当然看不出优先级的作用……
其实所谓优先级只有在长期稳定运行的系统中才有用,这个很难测试的……

这样啊。
  • 写回答

4条回答 默认 最新

  • fmjsjx 2011-05-12 17:28
    关注

    所谓线程优先级,个人理解只是对资源竞争的一个辨别依据,就是说当多个线程竞争资源时,具有较高优先级的线程会优先执行。
    楼主的线程执行过程太短、逻辑太简单,基本不存在竞争问题,当然看不出优先级的作用……
    其实所谓优先级只有在长期稳定运行的系统中才有用,这个很难测试的……

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的