Java多線程處理任務的封裝

jopen 9年前發布 | 12K 次閱讀 多線程 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)+",任務成功數"+result.size());
    }

    /**
     * Created with IntelliJ IDEA.
     * 執行任務,返回所有執行的結果
     * className: TaskMulThreadService
     *
     * @author: ddys
     * @version 1.0
     * Date Time:
     */
    public Boolean execute(String s) {
        System.out.println(Thread.currentThread().getId()+"線程正在處理"+s);
        return true;
    }
}

2.附帶一個查詢任務的方法,實現這個查詢任務方法和業務處理方法,然后執行返回處理結果

代碼如下:

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)+",任務成功數"+result.size());
    }
    /**
     * Created with IntelliJ IDEA.
     * 執行任務,返回所有執行的結果
     * 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 傳遞參數
     * @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;
    }
}

項目主頁:http://www.baiduhome.net/lib/view/home/1447752058822

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!