参考:Java多线程-线程池ThreadPoolExecutor的submit返回值Future
1、无返回值:execute
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 30; i++) {
final int finalI = i;
Runnable runnable = new Runnable(){
@Override
public void run() {
SystemClock.sleep(3000);
Log.d("google_lenve_fb", "run: "+ finalI);
}
};
//submit
fixedThreadPool.execute(runnable);
}
fixedThreadPool.shutdown();
2、有返回值:submit
ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
List<Future> futures = new ArrayList<>();
for (int i = 0; i < 30; i++) {
final int finalI = i;
//创建一个Callable,3秒后返回String类型
Callable myCallable = new Callable() {
@Override
public String call() throws Exception {
Thread.sleep(3000);
Log.e(TAG,"calld方法执行了 " + finalI);
return "call方法返回值"+ finalI;
}
};
Future temp = fixedThreadPool.submit(myCallable);
futures.add(temp);
//fixedThreadPool.execute(runnable);
}
try {
//遍历所有任务的执行结果
for (Future future : futures) {
Log.e(TAG, "submit: " + future.get());
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}