Java 多線程處理任務(wù)的封裝
最近公司項(xiàng)目很多地方使用多線程處理一些任務(wù),邏輯代碼和java多線程處理代碼混合在一起,造成代碼的可讀性超級差,現(xiàn)在把Java多線程相關(guān)的處理抽出來,方面代碼中重復(fù)使用。抽的不好,歡迎大家拍磚
 
最近公司項(xiàng)目很多地方使用多線程處理一些任務(wù),邏輯代碼和java多線程處理代碼混合在一起,造成代碼的可讀性超級差,現(xiàn)在把Java多線程相關(guān)的處理抽出來,方面代碼中重復(fù)使用。抽的不好,歡迎大家拍磚
使用方法很簡單,有兩種使用方法
1.直接傳遞一批任務(wù)給到多線程處理方法,返回處理結(jié)果
代碼如下:
- /**
 - * Created with IntelliJ IDEA.
 - * 測試多線程處理任務(wù)
 - * 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]="任務(wù)"+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("任務(wù)處理失敗");
 - }
 - }
 - System.out.println("所有任務(wù)處理完成,耗時(shí)"+(System.currentTimeMillis()-start)+",任務(wù)成功數(shù)"+result.size());
 - }
 - /**
 - * Created with IntelliJ IDEA.
 - * 執(zhí)行任務(wù),返回所有執(zhí)行的結(jié)果
 - * className: TaskMulThreadService
 - *
 - * @author: ddys
 - * @version 1.0
 - * Date Time:
 - */
 - public Boolean execute(String s) {
 - System.out.println(Thread.currentThread().getId()+"線程正在處理"+s);
 - return true;
 - }
 - }
 
2.附帶一個(gè)查詢?nèi)蝿?wù)的方法,實(shí)現(xiàn)這個(gè)查詢?nèi)蝿?wù)方法和業(yè)務(wù)處理方法,然后執(zhí)行返回處理結(jié)果
代碼如下:
- 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("任務(wù)處理失敗");
 - }
 - }
 - System.out.println("所有任務(wù)處理完成,耗時(shí)"+(System.currentTimeMillis()-start)+",任務(wù)成功數(shù)"+result.size());
 - }
 - /**
 - * Created with IntelliJ IDEA.
 - * 執(zhí)行任務(wù),返回所有執(zhí)行的結(jié)果
 - * 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: 獲取一批任務(wù)
 - * @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]="任務(wù)"+i;
 - }
 - return taskItems;
 - }
 - }
 
責(zé)任編輯:王雪燕 
                    來源:
                    codeceo
 














 
 
 







 
 
 
 