1. 线程分类
a. 无返回值Runnable,
b. 有返回值Callable
2. 线程创建
new Thread(Runnable runnable);
无返回值的线程:
new Thread(() -> System.out.println("run runnable")).start();
有返回值的线程
FutureTask<Integer> futureTask = new FutureTask<>(() -> {
return -1;
});
new Thread(futureTask).start();
Integer integer = futureTask.get();
FutureTask本身是一个Runnable, 包含成员变量outcome用来存放结果,部分源码如下:
3. 使用线程池创建
@Test
public void test04() throws InterruptedException, ExecutionException {
ExecutorService executor = Executors.newCachedThreadPool();
//Runnable
executor.execute(() -> {
System.out.println("executor runnable");
});
//Callable
List<Callable<Integer>> taskList = Arrays.asList(new Callable[]{new Callable<Integer>() {
@Override
public Integer call() throws Exception {
return -1;
}
}});
List<Future<Integer>> futures = executor.invokeAll(taskList);
for (Future<Integer> future : futures) {
System.out.println(future.get());
}
}