有很多方法可以做你想要的 . 您需要小心,不要最终创建太多线程 .
以下是一个示例,您可以使用ExecutorCompletionService提高效率,也可以使用Runnable .
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadsMakeThreads {
public static void main(String[] args) {
new ThreadsMakeThreads().start();
}
public void start() {
//Create resources
ExecutorService threadPool = Executors.newCachedThreadPool();
Random random = new Random(System.currentTimeMillis());
int numberOfThreads = 5;
//Prepare threads
ArrayList leaders = new ArrayList();
for(int i=0; i < numberOfThreads; i++) {
leaders.add(new Leader(threadPool, random));
}
//Get the results
try {
List> results = threadPool.invokeAll(leaders);
for(Future result : results) {
System.out.println("Result is " + result.get());
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
threadPool.shutdown();
}
class Leader implements Callable {
private ExecutorService threadPool;
private Random random;
public Leader(ExecutorService threadPool, Random random) {
this.threadPool = threadPool;
this.random = random;
}
@Override
public Integer call() throws Exception {
int numberOfWorkers = random.nextInt(10);
ArrayList workers = new ArrayList();
for(int i=0; i < numberOfWorkers; i++) {
workers.add(new Worker(random));
}
List> tasks = threadPool.invokeAll(workers);
int result = 0;
for(Future task : tasks) {
result += task.get();
}
return result;
}
}
class Worker implements Callable {
private Random random;
public Worker(Random random) {
this.random = random;
}
@Override
public Integer call() throws Exception {
return random.nextInt(100);
}
}
}