Java 多線程處理任務的封裝
最近公司項目很多地方使用多線程處理一些任務,邏輯代碼和java多線程處理代碼混合在一起,造成代碼的可讀性超級差,現(xiàn)在把Java多線程相關的處理抽出來,方面代碼中重復使用。抽的不好,歡迎大家拍磚
最近公司項目很多地方使用多線程處理一些任務,邏輯代碼和java多線程處理代碼混合在一起,造成代碼的可讀性超級差,現(xiàn)在把Java多線程相關的處理抽出來,方面代碼中重復使用。抽的不好,歡迎大家拍磚
使用方法很簡單,有兩種使用方法
1.直接傳遞一批任務給到多線程處理方法,返回處理結果
代碼如下:
- /**
- * Created with IntelliJ IDEA.
- * 測試多線程處理任務
- * className: TaskMulThreadServiceTest
- *
- * @version 1.0
- * Date Time: a
- *@author: ddys
- */
- public class TaskMulThreadServiceTest extends TestCase implements ITaskHandle<String,Boolean>{
- public void testExecute() throws Exception {
- String [] taskItems = new String[100];
- for (int i=0;i<100;i++){
- taskItems[i]="任務"+i;
- }
- IMulThreadService<String,Boolean> mulThreadService = new TaskMulThreadService(this);
- long start = System.currentTimeMillis();
- List<Boolean> result = mulThreadService.execute(taskItems);
- for (Boolean e : result){
- if(!e){
- System.out.println("任務處理失敗");
- }
- }
- System.out.println("所有任務處理完成,耗時"+(System.currentTimeMillis()-start)+",任務成功數(shù)"+result.size());
- }
- /**
- * Created with IntelliJ IDEA.
- * 執(zhí)行任務,返回所有執(zhí)行的結果
- * className: TaskMulThreadService
- *
- * @author: ddys
- * @version 1.0
- * Date Time:
- */
- public Boolean execute(String s) {
- System.out.println(Thread.currentThread().getId()+"線程正在處理"+s);
- return true;
- }
- }
2.附帶一個查詢?nèi)蝿盏姆椒?,實現(xiàn)這個查詢?nèi)蝿辗椒ê蜆I(yè)務處理方法,然后執(zhí)行返回處理結果
代碼如下:
- ate Time: a
- *@author: XWK
- */
- public class SelectTaskMulThreadServiceTest extends TestCase implements ISelectTask<String,Boolean>{
- public void testExecute() throws Exception {
- IMulThreadService<String,Boolean> mulThreadService = new SelectTaskMulThreadService(this);
- long start = System.currentTimeMillis();
- List<Boolean> result = mulThreadService.execute();
- for (Boolean e : result){
- if(!e){
- System.out.println("任務處理失敗");
- }
- }
- System.out.println("所有任務處理完成,耗時"+(System.currentTimeMillis()-start)+",任務成功數(shù)"+result.size());
- }
- /**
- * Created with IntelliJ IDEA.
- * 執(zhí)行任務,返回所有執(zhí)行的結果
- * className: TaskMulThreadService
- *
- * @author: ddys
- * @version 1.0
- * Date Time:
- */
- public Boolean execute(String s) {
- System.out.println(Thread.currentThread().getId()+"線程正在處理"+s);
- return true;
- }
- /**
- * @param 'a 傳遞參數(shù)
- * @return a 回類型
- * @throws
- * @Title: a
- * @Description: 獲取一批任務
- * @author ddys
- * @date 2015-11-15 21:09
- */
- public String[] getTaskItem() {
- String [] taskItems = new String[100];
- for (int i=0;i<100;i++){
- taskItems[i]="任務"+i;
- }
- return taskItems;
- }
- }
責任編輯:王雪燕
來源:
codeceo