Future的get()方法是阻塞的, 需要优化才可以实现异步多线程, 示例如下所示.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class TestFuture {
private static final int THREAD_SIZE = 10;
private static final int USER_NUM = 55;
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(THREAD_SIZE); //线程池
List<Future<Boolean>> futureList = new ArrayList<>(THREAD_SIZE); //future缓存队列
int count = (int)Math.ceil((USER_NUM*1.0f)/THREAD_SIZE);
System.out.println("count="+count);
for (int i = 0; i < count; i++) {
for (int j = 0; j < THREAD_SIZE; j++) {
CountNum countNum = new CountNum();
Future<Boolean> future = executor.submit(countNum);
futureList.add(future);
}
for(Future<Boolean> f: futureList){
try {
Boolean ret = f.get(); //会阻塞
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
executor.shutdown(); //关闭线程池
System.out.println("================");
}
}
//具体线程任务
class CountNum implements Callable<Boolean>{
@Override
public Boolean call() throws Exception {
System.out.println(Thread.currentThread().getId()+" start");
Thread.sleep(50);
System.out.println(Thread.currentThread().getId()+" end");
return true;
}
}
|