6
我目前正在學習Java中的線程基礎知識,並且正在嘗試編寫一個簡單的線程組程序。雖然我得到了不同類型的輸出,但我和教程網站一樣寫了它。下面是我的代碼,我得到不同的輸出。Java中的ThreadGroup
public class ThreadGroupDemo implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
// get the name of the current thread.
}
public static void main(String[] args) {
ThreadGroupDemo runnable = new ThreadGroupDemo();
ThreadGroup tg1 = new ThreadGroup("Parent Group");
// Creating thread Group.
Thread t1 = new Thread(tg1, new ThreadGroupDemo(), "one");
t1.start();
t1.setPriority(Thread.MAX_PRIORITY);
Thread t2 = new Thread(tg1, new ThreadGroupDemo(), "second");
t2.start();
t2.setPriority(Thread.NORM_PRIORITY);
Thread t3 = new Thread(tg1, new ThreadGroupDemo(), "Three");
t3.start();
System.out.println("Thread Group name : " + tg1.getName());
tg1.list();
}
}
我越來越 輸出:
Thread Group name : Parent Group
Three
java.lang.ThreadGroup[name=Parent Group,maxpri=10]
second
one
Thread[one,10,Parent Group]
Thread[second,5,Parent Group]
Thread[Three,5,Parent Group]
輸出應該是這樣的:
one
two
three
Thread Group Name: Parent ThreadGroup
java.lang.ThreadGroup[name=Parent ThreadGroup,maxpri=10]
Thread[one,5,Parent ThreadGroup]
Thread[two,5,Parent ThreadGroup]
Thread[three,5,Parent ThreadGroup]
我不能夠理解爲什麼會這樣呢?設置優先級可以幫助它嗎?
答案很簡單:本教程是錯誤的。唯一確實保證的是線程組名將出現在線程組列表之前。 – biziclop
http://www.javatpoint.com/threadgroup-in-java –
這很震撼。我建議你改用[官方教程](https://docs.oracle.com/javase/tutorial/essential/concurrency/)。並且忘掉[線程組](http://stackoverflow.com/questions/3265640/why-threadgroup-is-being-criticised),無論如何它們都是無用的。設置線程的優先級也是如此。 – biziclop