定义MyCallable,实现Callable接口:
package com.team;
import java.util.concurrent.Callable;
public class MyCallable implements Callable<Long> {
private int max;
public MyCallable(int max) {
this.max = max;
}
@Override
public Long call() throws Exception {
System.out.println("子线程:" + Thread.currentThread().getName());
long result = 1;
for (int i = 1; i <= max; i++) {
result *= i;
}
return result;
}
}
定义主类:
package com.team;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class ThreadDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable1 = new MyCallable(3);
FutureTask<Long> futureTask1 = new FutureTask(myCallable1);
new Thread(futureTask1).start();
Long res1 = futureTask1.get();
System.out.println("返回结果是:" + res1);
MyCallable myCallable2 = new MyCallable(5);
FutureTask<Long> futureTask2 = new FutureTask(myCallable2);
new Thread(futureTask2).start();
Long res2 = futureTask2.get();
System.out.println("返回结果是:" + res2);
}
}
运行结果:
子线程:Thread-0
返回结果是:6
子线程:Thread-1
返回结果是:120