Callable與Future

Callable與Future
使用線程池來創建並行的任務:
這個一個簡單的demo,可以在最後統一獲取執行結果;以此類推
方案一:

ExecutorService threadPool = Executors.newFixedThreadPool(2);
        Future<Integer> future = threadPool.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                return 1;
            }
        });
        Future<Integer> futureNew = threadPool.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                return 2;
            }
        });
        try {
            System.out.println(future.get());
            System.out.println(futureNew.get());
        } catch (Exception e) {
            e.printStackTrace();
        }

企業應用:

 public static void main(String[] args) throws ParseException {
        try{
            ThreadPoolExecutor threadPool = ImportDataThreadPoolUtil.getInstance();
            FutureTask<Boolean> futureTask = new FutureTask(new Callable() {
                public Boolean call() throws Exception {
                    //do something
                    return null;
                }
            });
            threadPool.execute(futureTask);
            Boolean flag = false;
            Long userTime = 0L;
            while (userTime < 10) {
                flag = futureTask.get();
                if (futureTask.isDone() ) {
                    break;
                }
                Thread.sleep(500);//線程鎖定
                userTime++;
            }
        }catch (Exception e){
            System.out.println("error ~~");
        }
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章