zoukankan      html  css  js  c++  java
  • Java多线程编程(二)

    在 Java多线程编程(一) 中的多线程并没有返回值,本文将介绍带返回值的多线程。

    要想有返回值,则需要实现新的接口Callable而不再是Runnable接口,实现的方法也改为call()方法,执行器也不再是调用execute(),而是submit()

    【程序实例】

     1 public class TaskWithResult implements Callable<String> {
     2 
     3     private int id;
     4 
     5     public TaskWithResult(int id) {
     6         this.id = id;
     7     }
     8 
     9     @Override
    10     public String call() throws Exception {
    11         return "result of TaskWithResult " + id + " : sum() = " + Sum(id);
    12     }
    13 
    14     private int Sum(int id) {
    15         return (id * (id + 1)) / 2;
    16     }
    17 
    18 }
     1 public class Main {
     2 
     3     public static void main(String[] args) {
     4         ExecutorService exec = Executors.newCachedThreadPool();
     5         ArrayList<Future<String>> results = new ArrayList<Future<String>>();
     6         for (int i = 0; i < 10; i++)
     7             results.add(exec.submit(new TaskWithResult(i)));
     8         for (Future<String> fs : results)
     9             try {
    10                 System.out.println(fs.get());
    11             } catch (InterruptedException e) {
    12                 System.out.println(e);
    13                 return;
    14             } catch (ExecutionException e) {
    15                 System.out.println(e);
    16             } finally {
    17                 exec.shutdown();
    18             }
    19     }
    20 
    21 }

    【运行结果】

     1 result of TaskWithResult 0 : sum() = 0
     2 result of TaskWithResult 1 : sum() = 1
     3 result of TaskWithResult 2 : sum() = 3
     4 result of TaskWithResult 3 : sum() = 6
     5 result of TaskWithResult 4 : sum() = 10
     6 result of TaskWithResult 5 : sum() = 15
     7 result of TaskWithResult 6 : sum() = 21
     8 result of TaskWithResult 7 : sum() = 28
     9 result of TaskWithResult 8 : sum() = 36
    10 result of TaskWithResult 9 : sum() = 45
  • 相关阅读:
    Discuz X3.2 分区 gid 完美伪静态方法 Apache/Nginx
    如何批量转换 WordPress 文章分类
    修改 WordPress 文件上传目录
    如何验证 jemalloc 优化 Nginx 是否生效
    .Net Core 1.1 + CentOs 7 环境配置
    DotNet Core中使用dapper
    爬虫 HttpHelper
    iTextSharp 不适用模板 代码拼接PDF
    .Net中的加密解密
    .Net Core使用 MiniProfiler 进行性能分析
  • 原文地址:https://www.cnblogs.com/acode/p/5787093.html
Copyright © 2011-2022 走看看