Java的多线程操作

需要执行多线程操作(对某个方法执行)

1. 执行方法不固定,参数不固定,返回类型不固定(当前是固定的)。

2. 在已有的项目上做迭代,要求改动越小越好。

 1 /**
 2    * 执行多线程操作 默认:20线程 30S最大等待时间 异常不抛出
 3    *
 4    * @param param 参数List
 5    * @param function 函数<Object, Result>
 6    */
 7   public List<Object> multiThreadSpiderFunc(List<Object> param, Function<Object, Result> function)
 8       throws Exception {
 9     return multiThreadFunc(param, function, 20, 30, Boolean.FALSE);
10   }
11 
12   public List<Object> multiThreadFunc(List<Object> param, Function<Object, Result> function,
13       Integer maxThreadPool, Integer maxWaitTime, Boolean throwException) throws Exception {
14     Integer size = maxThreadPool;
15     ExecutorService threadPool = Executors.newFixedThreadPool(size);
16     List<Future> futureList = new ArrayList<>(size);
17 
18     for (Integer i = 0; i < param.size(); i++) {
19       Callable callableThread = new CallableThread(param.get(i), function);
20       Future f = threadPool.submit(callableThread);
21       futureList.add(f);
22     }
23     List<Object> resultList = new ArrayList();
24     // 获取所有并发结果
25     for (Future future : futureList) {
26       try {
27         resultList.add(future.get(maxWaitTime, TimeUnit.SECONDS));
28       } catch (InterruptedException e) {
29         //中断异常
30         logger().println("中断异常:" + e);
31       } catch (ExecutionException e) {
32         //程序抛出异常
33         logger().println("程序抛出异常:" + e);
34         if (throwException) {
35           //线程池销毁
36           threadPool.shutdownNow();
37           throw e;
38         }
39       } catch (TimeoutException e) {
40         //超时异常
41         logger().println("超时异常:" + e);
42       } finally {
43         future.cancel(true);
44       }
45     }
46     threadPool.shutdown();
47     return resultList;
48   }
49 
50   public class CallableThread implements Callable {
51 
52     /**
53      * 多线程参数
54      */
55     volatile Object param;
56     /**
57      * 函数
58      */
59     volatile Function<Object, Result> function;
60 
61     public CallableThread(Object param, Function<Object, Result> function) {
62       this.param = param;
63       this.function = function;
64     }
65 
66     @Override
67     public Result call() {
68       try {
69         ThreadSpiderParam paramObj = (ThreadSpiderParam) param;
70         Thread.currentThread().setName(paramObj.getThreadName());
71       } catch (Exception e) {
72         logger().println(e);
73         logger().println("设置线程名称异常 使用系统默认命名");
74       }
75 
76       return function.apply(param);
77     }
78   }

多线程的基础学习 参考:https://www.cnblogs.com/yishilin/p/8436303.html

猜你喜欢

转载自www.cnblogs.com/yishilin/p/10862634.html