1. 程式人生 > >Java的多線程操作

Java的多線程操作

tps 線程 href i++ exce reads 函數 中斷 sub

需要執行多線程操作(對某個方法執行)

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

Java的多線程操作