2016-02-01 47 views
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] 

我不能夠理解爲什麼會這樣呢?設置優先級可以幫助它嗎?

+0

答案很簡單:本教程是錯誤的。唯一確實保證的是線程組名將出現在線程組列表之前。 – biziclop

+5

http://www.javatpoint.com/threadgroup-in-java –

+4

這很震撼。我建議你改用[官方教程](https://docs.oracle.com/javase/tutorial/essential/concurrency/)。並且忘掉[線程組](http://stackoverflow.com/questions/3265640/why-threadgroup-is-being-criticised),無論如何它們都是無用的。設置線程的優先級也是如此。 – biziclop

回答

3

即使擁有一定的優先級,您也無法預測線程的執行順序。您無法控制調度。這是你的操作系統決定的。

一本好書,關於併發在Java中:Java concurrency in practice

+0

此外,即使家庭計算機現在有多個核心,能夠實際運行並行多線程。這使得新開始的線程更有可能計劃立即運行。 – biziclop