一旦我的所有线程完成执行,我怎样才能运行我的最后一个线程来运行?

时间:2013-11-02 11:05:40

标签: java multithreading

假设我有X个线程以并行模式运行,同时我希望我的新线程只在所有X号码完成后运行?

4 个答案:

答案 0 :(得分:0)

如果您需要多个具有不同线程数的阶段,请使用CyclicBarrierPhaser

答案 1 :(得分:0)

您可以使用CountDownLatch。只是

  • 在Latch构造函数中设置n
  • 在每个工作线程结束时使用yourLatchInstance.countDown()
  • 在等待线程使用await()开始时。在调用countDown() n次后,等待线程将被释放。

DEMO

答案 2 :(得分:0)

for (Thread thread: threads)
  thread.join();

new MyNewThread().start()

答案 3 :(得分: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)括起来。阻止。