我想编写一个了解线程已完成并启动新线程的线程。 我的意思是我写了这段代码:
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.
}
答案 0 :(得分: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() {
}
});
}
答案 1 :(得分: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();
}
答案 2 :(得分: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(...)
}
});