Java 线程池执行器

标签 java multithreading runnable

我在理解 Java ThreadPoolExecutor 时遇到了很大的困难。例如,我想计算数字1-1000的平方:

public static void main(String[] args) throws InterruptedException, ExecutionException {

    Callable<ArrayList<Integer>> c = new squareCalculator(1000);
    ExecutorService executor = Executors.newFixedThreadPool(5);
    Future<ArrayList<Integer>> result = executor.submit(c);


    for(Integer i: result.get()){
        System.out.println(i);
    }

}

还有

public class squareCalculator implements Callable<ArrayList<Integer>>{
    private int i;
    private int max;

    private int threadID;
    private static int id;
    private ArrayList<Integer> squares;

    public squareCalculator(int max){
        this.max = max;
        this.i = 1;
        this.threadID = id;
        id++;
        squares = new ArrayList<Integer>();

    }

    public ArrayList<Integer> call() throws Exception {
        while(i <= max){            
            squares.add(i*i);
            System.out.println("Proccessed number " +i + " in thread "+this.threadID);
            Thread.sleep(1);
            i++;
        }
        return squares;

    }
}

现在我的问题是,我只有一个线程进行计算。我预计会得到 5 个线程。

最佳答案

如果您希望Callable同时运行5次,则需要提交它5次。 您只提交了一次,然后询问了 5 次结果。

submit() 的 Javadoc:

Submits a value-returning task for execution and returns a Future representing the pending results of the task. The Future's get method will return the task's result upon successful completion.

您会看到 submit() 的 Javadoc 使用单数形式表示“task”,而不是“tasks”。

修复很简单:多次提交:

Future<ArrayList<Integer>> result1 = executor.submit(c);
Future<ArrayList<Integer>> result2 = executor.submit(c);
Future<ArrayList<Integer>> result3 = executor.submit(c);
/// etc..

result1.get();
result2.get();
result3.get();
// etc..

关于Java 线程池执行器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24595921/

相关文章:

java - 如何从 ByteBuffer 转换为 Avro 字节?

java - 如何使用parcelable将线程类对象从一个 Activity 传递到另一个 Activity

java - 使用假设角色同时访问属于不同帐户的两个 dynamodb 表不起作用

java - Android 动态删除处理程序 postDelayed

java - 如何通过 Runnable 修改事件

java - ManagedProperty/Bean 注入(inject)导致 NullPointer

Linux/POSIX : Why doesn't fork() fork *all* threads

c# - InvokeRequired 在自定义控件锁定表单 UI 中

objective-c - 单例的线程安全实例化

java - 创建基本动画