• 02027_线程池练习:返回两个数相加的结果


    1、要求:通过线程池中的线程对象,使用Callable接口完成两个数求和操作。

    2、代码实现:

      (1)Callable接口实现类

     1 import java.util.concurrent.Callable;
     2 
     3 public class MyCallable implements Callable<Integer> {
     4     // 成员变量
     5     int x = 5;
     6     int y = 3;
     7 
     8     // 构造方法
     9     public MyCallable() {
    10     }
    11 
    12     public MyCallable(int x, int y) {
    13         this.x = x;
    14         this.y = y;
    15     }
    16 
    17     @Override
    18     public Integer call() throws Exception {
    19         return x + y;
    20     }
    21 }

      (2)测试类

     1 import java.util.concurrent.ExecutionException;
     2 import java.util.concurrent.ExecutorService;
     3 import java.util.concurrent.Executors;
     4 import java.util.concurrent.Future;
     5 
     6 public class ThreadPoolDemo {
     7     public static void main(String[] args) throws InterruptedException,
     8             ExecutionException {
     9         // 创建线程池对象
    10         ExecutorService threadPool = Executors.newFixedThreadPool(2);
    11 
    12         // 创建一个Callable接口子类对象
    13         // MyCallable c = new MyCallable();
    14         MyCallable c = new MyCallable(100, 200);
    15         MyCallable c2 = new MyCallable(10, 20);
    16 
    17         // 获取线程池中的线程,调用Callable接口子类对象中的call()方法, 完成求和操作
    18         // <Integer> Future<Integer> submit(Callable<Integer> task)
    19         // Future 结果对象
    20         Future<Integer> result = threadPool.submit(c);
    21         // 此 Future 的 get 方法所返回的结果类型
    22         Integer sum = result.get();
    23         System.out.println("sum=" + sum);
    24 
    25         // 再演示
    26         result = threadPool.submit(c2);
    27         sum = result.get();
    28         System.out.println("sum=" + sum);
    29         // 关闭线程池(可以不关闭)
    30 
    31     }
    32 }

    3、运行结果:

      

      

    l  Callable接口实现类

  • 相关阅读:
    php 之 没有mysql支持时的替代方案
    在php中使用sockets:从新闻组中获取文章
    PHP ON 阿里云的环境配置攻略
    java基础2
    java基础1
    连接查询(内连接)
    mysql数据约束
    mysql表中数据的增删改查2
    mysql表中数据的增删改查
    mysql表的增查改删
  • 原文地址:https://www.cnblogs.com/gzdlh/p/8099279.html
Copyright © 2020-2023  润新知