1

Когда я запускаю этот код, он дал мне IllegalArgumentException, тогда весь код был выполнен, но имя потока t было по умолчанию только одним, а не Mark в соответствии с кодом.thread.setPriority (0) дает 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:

IllegalArgumentException - Если приоритет не в диапазоне MIN_PRIORITY к MAX_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) 
Смежные вопросы