2016-11-27 7 views
0

私は複数のスレッド間の競合をシミュレートするコードを書いている中で、完成したスレッドの順序を取得し、そのレースの勝者を印刷し、スレッドの順番が終了しました。 私は勝者を決定することができましたが、私は終了し、すべてのスレッドの順序を印刷する方法を見つけ出すことはできません。ここでレースシミュレーションと勝者

は、今までのコードは、任意のヘルプです!

import java.util.concurrent.CountDownLatch; 
import java.util.concurrent.ExecutorService; 
import java.util.concurrent.Executors; 
import java.util.concurrent.TimeUnit; 

public class Runner { 
private static CountDownLatch latch = new CountDownLatch(3); 
private static String winner; 

public static synchronized void finished(String threadName) { 
    if (winner == null) { 
     winner = threadName; 
    } 
    latch.countDown(); 

} 

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


    ExecutorService threadPool = Executors.newFixedThreadPool(10); 

    for (int i = 0; i < 10; i++) { 
     threadPool.submit(new raceTrack("Racer "+i)); 
    } 
    threadPool.shutdown(); 
    threadPool.awaitTermination(1, TimeUnit.SECONDS); 

    try { 
     latch.await(); 
     System.out.println("The winner is : " + winner); 
    } 
    catch (InterruptedException e) { 
     System.out.println("No winner"); 
     Thread.currentThread().interrupt(); 
    } 

} 
} 



public class raceTrack implements Runnable { 

public String racerID; 

public raceTrack(String id) { 
    this.racerID = id; 
} 

@Override 
public void run() { 


    System.out.println(racerID); 

    try { 
     Thread.sleep(1000); 

    } catch (InterruptedException e1) { 
     e1.printStackTrace(); 
    } 
    finally { 
      Runner.finished(racerID); 
     } 
} 

} 
+0

スタートとして決定されます。 –

答えて

0

あなたはだけでなく、1つの文字列のスレッド名のリストを持つことができます。

private static List<String> threadList; 

public static synchronized void finished(String threadName) { 
    threadList.add(threadName); 
    latch.countDown(); 

} 

あなたは、リストを反復処理し、スレッドの順序を決定することができます。当選者には、アレイを使用して、単一の `winner`の文字列を置換することによって、list.get(0)

+0

プログラムは –

+0

あなたはちょうどこのリストを反復処理し、各ラインを印刷@MohamedKhaled ..実行し続けると、何も印刷されません。私は自分でこれを行うことができると思います。 System.out.printlnを置き換えます( "勝者は" +勝者)。ループごとに –

関連する問題