public class CallableTest {
public static void main(String[] args) {
/**
* 3.用FutureTask把Callable对象封装成线程任务对象(这是线程一)
*/
Callable c1 = new MyCallable(100);
FutureTask<String> future = new FutureTask<>(c1);
/**
* 4.把线程任务对象交给Thread处理
*/
Thread thread1 = new Thread(future);
/**
* 调用Thread的start方法启动线程
*/
thread1.start();
/**
* 这是线程二(同上)
*/
Callable c2 = new MyCallable(200);
FutureTask<String> future2 = new FutureTask<>(c2);
Thread thread2 = new Thread(future2);
thread2.start();
try {
/**
* 通过FutureTask的get方法 获取结果,并输出(线程一)
*/
String ture1 = future.get();
System.out.println("第一个结果: " + ture1);
} catch (Exception e) {
e.printStackTrace();
}
try {
/**
* 通过FutureTask的get方法 获取结果,并输出(线程二)
*/
String ture2 = future2.get();
System.out.println("第二个结果: " + ture2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 1.继承Callable 要写<>泛型
* 私有属性 + 有参构造器
*/
class MyCallable implements Callable<String> {
private int n;
public MyCallable(int n) {
this.n = n;
}
/**
* 2.重写call()方法
*/
@Override
public String call() throws Exception {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += i;
}
return "子线程总数为: + " + sum;
}
}
输出结果: