2016-11-18 67 views
0

問題 - 創建N個線程(例如3,名稱可以是線程1,線程2,線程3),它將以相反順序說HelloWorld,即第一線程-3會說HelloWorld,然後是Thread-2,然後是Thread-1。join()方法在我實現的代碼中無法正常工作

解決方法 - 上述問題可以通過各種方式解決,如使用易失性標誌來指示哪個線程必須運行或使用連接方法(以便線程1完成依賴於線程3上的線程2和線程2 )。 我想通過連接方法來解決這個問題。但它沒有給我適當的結果。請幫幫我。下面是我的程序 -

Thread [] previosThread = {null}; 
    int[] previousIndex = {0}; 
    for (int i=3; i>=1; i--) { 
     int currentIndex = i; 
     System.out.print("PreviousIndex--"+previousIndex[0]+" ; "); 
     System.out.println("CurrentIndex--"+currentIndex); 
     Thread newThread = new Thread("Thread-"+i) { 
      public void run() { 
       if(previousIndex[0]!=0 && previousIndex[0]==currentIndex+1) { 
        try { 
         previosThread[0].join(); 
        } catch (InterruptedException e) { 
         Thread.currentThread().interrupt(); 
        } 
       } 
       System.out.println(this.getName()+" is saying HelloWorld!!"); 
      } 
     }; 
     previosThread[0] = newThread; 
     previousIndex[0] = currentIndex; 
     newThread.start(); 
    } 

上述程序是給不確定的輸出像下面 -

PreviousIndex - 0; CurrentIndex - 3 PreviousIndex - 3; CurrentIndex - 2 PreviousIndex - 2; CurrentIndex - 1 線程2在說HelloWorld !! 線程1在說HelloWorld! 線程3在說HelloWorld!

+3

啓動一個線程需要很少的時間。你的循環很可能會在任何*線程實際進入run()方法之前完成,所以'previosThread [0]'引用* last *線程。所有3個線程都會看到最後一個值。 – Andreas

+0

@安德里亞斯:非常感謝。你解決了我的問題。 :) – malviyarahuljayendra

回答

0

根據Andreas的評論,我錯誤地使用了previosThread [0]。我沒有使用previosThread [0],而是維護了一個單獨的創建線程數組,以便我可以在新線程上正確調用join方法,然後以相反順序啓動此數組的每個線程,以便正確使用join方法,並且依賴線程應該運行。下面是我的代碼---

public class AntThread extends Thread { 

private Thread dependentThread; 
private String threadName; 
private int index; 
public AntThread(Thread dependentThread, String threadName, int index) { 
    super(threadName); 
    this.dependentThread = dependentThread; 
    this.threadName = threadName; 
    this.index = index; 
} 

public void run() { 
    if(dependentThread!=null) { 
     try { 
      dependentThread.join(); 
     } catch (InterruptedException e) { 
      this.interrupt(); 
     } 
    } 
    System.out.println(Thread.currentThread().getName()+" is saying - HelloWorld"); 
} 

}

和主類 -

公共類MultipleThreadsGreetingInReverseOrderTest {

public static void main(String[] args) throws InterruptedException { 

    int size = 10; 
    Thread [] createdThreads = new Thread[size]; 
    for(int i=size; i>0; i--) { 
     Thread dependentThread = null; 
     if(i!=size) 
      dependentThread = createdThreads[i]; 
     Thread antThread = new AntThread(dependentThread, "Thread-"+i, i); 
     createdThreads[i-1] = antThread; 
    } 

    //Starting the last thread first, as the join condition will work only when dependent thread is runnning 
    for(int j=createdThreads.length-1; j>=0; j--) { 
     createdThreads[j].start(); 
    } 

} 

}

非常感謝!安德烈亞斯爲快速反應。