您需要使用 Executor 服务来提交 Task
//Get ExecutorService from Executors utility class, thread pool size is 10
ExecutorService executor = Executors.newFixedThreadPool(10);
//create a list to hold the Future object associated with Callable
List<Future<Boolean>> list = new ArrayList<>();
//Create Callable instance
Callable<Boolean> callable = new HA(new Socket());
for(int i=0; i< 100; i++){
//submit Callable tasks to be executed by thread pool
Future<Boolean> future = executor.submit(callable);
//add Future to the list, we can get return value using Future
list.add(future);
}
for(Future<Boolean> fut : list){
try {
//print the return value of Future, notice the output delay in console
// because Future.get() waits for task to get completed
System.out.println(new Date()+ "::"+fut.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
//shut down the executor service now
executor.shutdown();
你的 Callable 可能如下
public static class HA implements Callable<Boolean> {
private Socket client;
public HA (Socket output) {
this.client = output;
}
@Override
public Boolean call() throws Exception {
Thread.sleep(1000);
//return the thread name executing this callable task
return true;
}
}