1

当我运行此代码时,它给了我IllegalArgumentException,然后执行了整个代码,但是线程t的名称仅默认为1,而不是代码中的标记。thread.setPriority(0)is IllegalArgumentException

可能是什么原因?

Exception in thread "main" java.lang.IllegalArgumentException 
     at java.lang.Thread.setPriority(Unknown Source) 
     at Threads.CurrentThreadImpl.main(CurrentThreadImpl.java:11) 
    value of I is : 0and the thread name is : Thread-0 
    value of I is : 1and the thread name is : Thread-0 
    value of I is : 2and the thread name is : Thread-0 
    value of I is : 3and the thread name is : Thread-0 
    value of I is : 0and the thread name is : Thread-1 
    value of I is : 1and the thread name is : Thread-1 
    value of I is : 2and the thread name is : Thread-1 
    value of I is : 3and the thread name is : Thread-1 

public class CreateThread implements Runnable{ 

    public void run(){ 
     for(int i = 0; i<4; i++){ 
      System.out.println("value of I is : "+ i + "and the thread name is : "+ Thread.currentThread().getName()); 
     } 
    } 
} 

    public class CurrentThreadImpl { 

    public static void main(String[] args) { 
     CreateThread runnableObj = new CreateThread(); 
     Thread thread = new Thread(runnableObj); 
     Thread t = new Thread(runnableObj); 
     thread.start(); 
     t.start(); 
     thread.setPriority(0); 
     t.setPriority(10); 
     t.setName("Mark"); 
    } 

} 
+1

见[这里](http://docs.oracle.com/ javase/6/docs/api/constant-values.html#java.lang.Thread.MAX_PRIORITY)MIN/MAX的优先级是多少 – A4L

回答

8

Thread#setPriority

- 如果优先级不在范围 MIN_PRIORITYMAX_PRIORITY

MIN_PRIORITY是1,而不是0:

enter image description here

+0

多数民众赞成可以...但如果我给错了优先级,即使代码工作。为什么它在发生错误后不会停止?有什么特定的原因吗? – user2450176

+1

@ user2450176执行线程创建的线程已停止,或者至少该方法突然完成。这就是为什么线程名称更改从未发生过。它开始的两个线程没有遇到任何异常,并继续运行。 –

4

优先级从1到10。

Thread.MIN_PRIORITY (1) 
Thread.NORM_PRIORITY (5) 
Thread.MAX_PRORITY (10) 
相关问题