• Java多线程的实战应用


    一.实现 Callable<String>接口,重写call()方法

     1 import com.google.common.collect.Lists;
     2 import java.util.List;
     3 import java.util.concurrent.Callable;
     4 import java.util.concurrent.ExecutorService;
     5 import java.util.concurrent.Executors;
     6 import java.util.concurrent.Future;
     7 
     8 public class JustTest2 {
     9     public static void main(String[] args) {
    10         Callable<String> callable = null;
    11         //创建大小为5的线程池
    12         ExecutorService executor = Executors.newFixedThreadPool(5);
    13         List<Future<String>> results = Lists.newArrayList();
    14 
    15         for (int i = 0; i < 10; i++) {
    16             callable = new TestCallable("data1", "data2",String.valueOf(i));
    17             Future<String> result = executor.submit(callable);
    18             //把结果都放入results集合中
    19             results.add(result);
    20         }
    21         //关闭线程池
    22         executor.shutdown();
    23 
    24         for (Future<String> result : results) {
    25             try {
    26                 //get()获取 返回的结果
    27                 System.out.println(result.get());
    28             } catch (Exception e) {
    29             }
    30         }
    31     }
    32 
    33 }
    34 
    35 /**
    36  * 内部类:实现Callable接口
    37  * 重写call()方法
    38  */
    39 class TestCallable implements Callable<String> {
    40     private String data1;
    41     private String data2;
    42     private String flag;
    43 
    44     public TestCallable(String data1, String data2,String flag) {
    45         this.data1 = data1;
    46         this.data2 = data2;
    47         this.flag = flag;
    48     }
    49 
    50     @Override
    51     public String call() {
    52         if(flag.equals("1")){
    53             return data1;
    54         }
    55         return data2;
    56     }
    57 }

    二,运行结果为

  • 相关阅读:
    FastAdmin Shopro商城安装
    MYSQL ERROR 10060
    宝塔命令
    kdevtmpfsi挖矿病毒处理
    VUE安装
    原生JS请求(AJAX)
    Bootstrap: 模态框组件
    Bootstrap: 缩略图组件
    Bootstrap: 栅格系统
    Bootstrap: 下拉菜单组件 & 分页组件
  • 原文地址:https://www.cnblogs.com/yy136/p/8324306.html
Copyright © 2020-2023  润新知