1. 程式人生 > >執行緒池execute/submit差異

執行緒池execute/submit差異

1、無返回值:execute

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
for (int i = 0; i < 30; i++) {
    final int finalI = i;

    Runnable runnable = new Runnable(){
        @Override
        public void run() {
            SystemClock.sleep(3000);
            Log.d("google_lenve_fb", "run: "+ finalI);
        }
    };
    //submit
    fixedThreadPool.execute(runnable);
}
fixedThreadPool.shutdown();

2、有返回值:submit

ExecutorService fixedThreadPool = Executors.newFixedThreadPool(3);
List<Future> futures = new ArrayList<>();
for (int i = 0; i < 30; i++) {
    final int finalI = i;

    //建立一個Callable,3秒後返回String型別
    Callable myCallable = new Callable() {
        @Override
        public String call() throws Exception {
            Thread.sleep(3000);
            Log.e(TAG,"calld方法執行了 " + finalI);
            return "call方法返回值"+ finalI;
        }
    };
    Future temp = fixedThreadPool.submit(myCallable);
    futures.add(temp);
    //fixedThreadPool.execute(runnable);
}
try {
    //遍歷所有任務的執行結果
    for (Future future : futures) {
        Log.e(TAG, "submit: " + future.get());
    }
} catch (InterruptedException e) {
    e.printStackTrace();
} catch (ExecutionException e) {
    e.printStackTrace();
}