thread.setPriority(0)给出了IllegalArgumentException

时间:2013-09-22 13:04:35

标签: java multithreading concurrency illegalargumentexception

当我运行此代码时,它给了我IllegalArgumentException,然后执行了整个代码,但是线程t的名称只是默认的一个而不是代码中的Mark。

可能是什么原因?

    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");
    }

}

2 个答案:

答案 0 :(得分:8)

请参阅Thread#setPriority

  

IllegalArgumentException - 如果优先级不在范围内    MIN_PRIORITY MAX_PRIORITY

MIN_PRIORITY是1,而不是0:

enter image description here

答案 1 :(得分:4)

优先级从1到10。

Thread.MIN_PRIORITY (1)
Thread.NORM_PRIORITY (5)
Thread.MAX_PRORITY (10)