简体   繁体   English

如何编写一个了解线程已完成并开始新线程的循环?

[英]How can I write a loop which understand a thread has finished and starts new thread?

I want to write a thread which understand a thread has finished and starts new thread. 我想编写一个线程,该线程了解线程已完成并开始新线程。 I mean I wrote this code : 我的意思是我写了这段代码:

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

But I want to do it in for loop. 但我想在for循环中做。 I want to create just 5 thread.But when a thread has finished I want to create a new one. 我只想创建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.
}

The thread class has these methods, which could be used to do what you want: 线程类具有以下方法,可用于执行所需的操作:

Thread.join()
Thread.isAlive()

But, you probably really want to use a thread pool, like this: 但是,您可能真的想使用线程池,如下所示:

    ExecutorService executor = Executors.newFixedThreadPool(5);
    for(int i=0;i<N;i++) {
        executor.submit(new Runnable() {
            @Override
            public void run() {
            }
        });
    }

If you want a more universal method, but more low level you can use a semaphore : 如果您想要一个更通用的方法,但更底层,则可以使用信号量

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();
}

You sounded like you want to create task base on the currently running task. 您听起来好像想基于当前正在运行的任务创建任务。 Here I have an example which you could create new task in another task. 这里有一个示例,您可以在另一个任务中创建新任务。 Perhaps, you may also want to look at java.util.concurrent.ForkJoinPool 也许,您可能还想看看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(...)
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM