0

我想写一个线程来理解线程已经完成并开始新线程。我的意思是我写了这段代码:

 new Thread(new Runnable(){ 
            @Override public void run(){
    //code here
                } 
           }).start();

但我想在 for 循环中做到这一点。我只想创建 5 个线程。但是当一个线程完成后,我想创建一个新线程。

for(int i=0;i<300;i++)
{
 //I want to create 5 thread here and stop code  and then when a thread has finished I want //to create  new thread.
}
4

3 回答 3

5

线程类有这些方法,可以用来做你想做的事:

Thread.join()
Thread.isAlive()

但是,您可能真的想使用线程池,如下所示:

    ExecutorService executor = Executors.newFixedThreadPool(5);
    for(int i=0;i<N;i++) {
        executor.submit(new Runnable() {
            @Override
            public void run() {
            }
        });
    }
于 2013-06-25T12:23:44.590 回答
1

如果您想要一种更通用但级别更低的方法,则可以使用信号量

final Semaphore s = new Semaphore(5);
for (int i = 0; i < 20; ++i)
{
    final int j = i;

    s.acquire();

    new Thread(new Runnable()
    {
        @Override
        public void run()
        {
            try
            {
                System.out.println("Thread " + j + " starts.");
                Thread.sleep(1000);
                System.out.println("Thread " + j + " ends.");
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
            finally
            {
                s.release();
            }
        }

    }).start();
}
于 2013-06-25T12:25:29.187 回答
0

您听起来像是要根据当前正在运行的任务创建任务。这里我有一个例子,你可以在另一个任务中创建新任务。也许,您可能还想看看java.util.concurrent.ForkJoinPool

final ExecutorService executorService = Executors.newFixedThreadPool(5);

executorService.submit(new Runnable(){
    @Override
    public void run() {
        //code here which run by 5 threads, thread can be reused when the task is finished

        //new task can be created at the end of another task
        executorService.submit(...)
    }
});
于 2013-06-25T12:25:34.913 回答