一、代码
package com.zjl.study;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Callable实现线程池 {
public static void main(String[] args) {
ExecutorService pools = Executors.newFixedThreadPool(3);
Future<String> t1 = pools.submit(new MyCallable(100));
Future<String> t2 = pools.submit(new MyCallable(200));
Future<String> t3 = pools.submit(new MyCallable(300));
Future<String> t4 = pools.submit(new MyCallable(400));
try {
System.out.println(t1.get());
System.out.println(t2.get());
System.out.println(t3.get());
System.out.println(t4.get());
} catch (Exception e) {
e.printStackTrace();
}
}
}
class MyCallable implements Callable<String> {
int n;
public MyCallable(int n) {
this.n = n;
}
@Override
public String call() throws Exception {
int sum = 0;
for (int i = 1; i <= n; i++) {
sum += n;
}
return Thread.currentThread().getName() + ":" + sum;
}
}
2、执行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/0dd3bea8fc805818c37c38a09cc5331e.png)