示例:
public class MultiThread {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MultiThread multiThread = new MultiThread();
// FutureTask<Integer> futureTask = new FutureTask<>(new Callable<Integer>() {
// @Override
// public Integer call() throws Exception {
// int i = 0;
// for (; i < 100; i++) {
// System.out.println(Thread.currentThread().getName() + "的循环变量i的值:" + i);
// }
// return i;
// }
// });
FutureTask<Integer> futureTask = new FutureTask<>( (Callable<Integer>) ()-> {
int i = 0;
for ( ; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + "的循环变量i的值:" + i);
}
return i;
});
for (int j = 0; j < 100; j++) {
System.out.println(Thread.currentThread().getName() + "的循环变量j的值:" + j);
if (j == 10) {
new Thread(futureTask, "有返回值的线程").start();
}
}
System.out.println("子线程的返回值:" + futureTask.get());
}
}
|