Callable接口线程池执行任务实例
package thread;
import java.util.ArrayList;
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;
/**
* Callable接口线程池执行任务实例
*
* @author .
* @since .
*/
public class MyThread {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ArrayList<Future> futures = new ArrayList<Future>();
// Executors用于创建各种类型线程池
ExecutorService executorService = Executors.newFixedThreadPool(3);
for (int i = 0; i < 100; i++) {
Future<?> future = executorService.submit(new Task1());
futures.add(future);
}
for (Future future : futures) {
//future.get()会使main线程阻塞
Object result = future.get();
System.out.println(result);
}
executorService.shutdown();
}
}
class Task1 implements Callable<String> {
public String call() throws Exception {
Thread.sleep(5000);
return Thread.currentThread().getName();
}
}