1

下面的代码:

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadTest {

    private static int counter = 0; 
    private static ExecutorService executorService = Executors.newCachedThreadPool();
    private static List<Integer> intValues = new ArrayList<Integer>();

    public static void main(String args[]){
        for(int counter = 0; counter < 10; ++counter){
            intValues.add(testCallback());
        }

        for(int i : intValues){
            System.out.println(i);
        }

        System.exit(0);
    }

    public static Integer testCallback() {

        Future<Integer> result = executorService.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                counter += 1;
                Thread.sleep(500);
                return counter;
            }
        });

        try {
            return result.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        return null;
    }
}

输出:

1
2
3
4
5
6
7
8
9
10

该程序运行大约需要 5 秒。我正在尝试在单独的线程中执行 testCallback 方法的多次调用,因此我希望此方法同时在 10 个线程中运行,其中每个线程使用大约 500 毫秒的时间。所以总的来说,我希望程序在 < 1 秒内运行。

为什么没有在单独的线程中同时调用计数器?

4

1 回答 1

10
result.get();

This is a blocking call that waits for the task to complete.

Therefore, you're waiting for each task to finish before starting the next one.

于 2013-09-10T15:00:55.077 回答