0

X 個のスレッドが並列モードで実行されていると同時に、X 個のすべてのスレッドが終了した後にのみ新しいスレッドを実行したいとしますか?

4

4 に答える 4

0

CyclicBarrier、または、Phaserそれぞれに異なる数のスレッドを持つ複数のステージが必要な場合は、を使用します。

于 2013-11-02T11:26:05.247 に答える
0

使用できますCountDownLatch。ただ

  • nラッチコンストラクターで設定
  • 各ワーカー スレッドの使用の最後にyourLatchInstance.countDown()
  • 待ちスレッド使用開始時await()。待機中のスレッドが解放される回数countDown()が呼び出された後。n

デモ

于 2013-11-02T11:26:14.417 に答える
0

これを試して:

    public class Main {

    /** The initial number of threads launched*/
    public static final int INITIAL_THREADS = 10;

    /** When less than MIN_THREADS are running, a new Thread is thrown. */ 
    public static final int MIN_THREADS = 5;

    /**  */
    public static final int TOTAL_THREADS_TO_PROCESS = 30;


    /** Launches INITIAL_THREADS and ends  */
    public static void main(String[] args){


            for(int i=0; i<INITIAL_THREADS; i++)
                new Thread( new MyThread() ).start();
        }

}


class MyThread implements Runnable{

    /** Stores the number of Threads runnning running. */
    private static int threadsRunning = 0;

    /** Stores the number of total thread processed.  Used as a exit confition */
    private static int threadProcessed = 0;


    @Override
    public  void run(){

        //With this synchronized block we modify the threadsRunning safely
        //synchronized(this)  <- Not valid because Threads objects are
        //  not the same instance.
        synchronized(MyThread.class){
            threadsRunning++;
            threadProcessed++;

            System.out.println("Threads running:" + threadsRunning +
                               ", Total Threads processed:" + threadProcessed +".");
        }


        //Thread Code here.  I simulate it with a 10 second sleep.
        try {
            Thread.sleep(10000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        //Needed to read/write threadsRunning and threadProcessed safely
        synchronized(MyThread.class){

            threadsRunning--;

            if(threadsRunning < Main.MIN_THREADS &&
                    threadProcessed < Main.TOTAL_THREADS_TO_PROCESS)

                new Thread( new MyThread() ).start();
        }
    }
}

特定の瞬間に、実行中のプロセスが 5 つ未満になることがわかります。これは、スレッドが終了し、システムが、最初のスレッドによって開始された新しいスレッドが起動される (まだ待機している) 前に終了する別のスレッドを続行するためです。プロセスが重い場合 (例では、10 秒を 100 以上変更した場合)、この可能性は低くなります。

たとえば、run メソッドの途中で計算される変数など、別の終了条件を使用する場合は、静的にすることを忘れないでください。その変数への読み取り/書き込みは、synchronized(MyThread.class) ブロックで囲む必要があります。

于 2013-11-02T12:33:15.043 に答える
0
for (Thread thread: threads)
  thread.join();

new MyNewThread().start()
于 2013-11-02T11:42:13.470 に答える