如何编写一个理解线程已完成并启动新线程的循环?

Ers*_*har 0 java multithreading

我想写一个线程,了解一个线程已经完成并启动新线程.我是说我写了这段代码:

 new Thread(new Runnable(){ 
            @Override public void run(){
    //code here
                } 
           }).start();
Run Code Online (Sandbox Code Playgroud)

但是我想在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.
}
Run Code Online (Sandbox Code Playgroud)

Kei*_*ith 5

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

Thread.join()
Thread.isAlive()
Run Code Online (Sandbox Code Playgroud)

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

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