- package com.kxg_07;
- import java.util.concurrent.Callable;
- public class MyCallable implements Callable<Integer> {
-
- private int number;
- // 定义带参构造
- public MyCallable(int number) {
- this.number = number;
- }
- @Override
- public Integer call() throws Exception {
- // 定义参数用来接收和
- int sum = 0;
-
- // 求出和
- for (int i = 0; i < number; i++) {
- sum += i;
- }
-
- // 返回和
- return sum;
- }
- }
复制代码- package com.kxg_07;
- /*
- * 利用Callable实现多线程求和
- *
- *
- * Future<?> submit(Runnable task):添加Runnable实现类
- */
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- public class CallableDemo {
- public static void main(String[] args) throws InterruptedException,
- ExecutionException {
- // 创建线程池
- ExecutorService pool = Executors.newFixedThreadPool(2);
- // 添加线程到线程中,添加方法是submit(),其返回值是Future<T>接口,用此接口接收
- // <T> Future<T> submit(Callable<T> task):添加Callable实现类
- Future<Integer> f1 = pool.submit(new MyCallable(100));
- Future<Integer> f2 = pool.submit(new MyCallable(50));
-
- // 用Future<T>接口下的T get()方法,得到Future<T>接口的泛型类型返回值,也就是线程的返回值
- Integer i1 = f1.get();
- Integer i2 = f2.get();
-
- // 输出结果
- System.out.println(i1);
- System.out.println(i2);
- // 结束线程池
- pool.shutdown();
- }
- }
复制代码
|
|