java - 在 Java 1.6 中使用 For 循环和多线程

标签 java multithreading

我正在尝试在 Java 1.6 中使用带有多线程的 For 循环。我尝试使用流,但显然它是在 Java 1.8 中添加的,所以我尝试使用ExecutorService 和 Future,但我无法使其工作。

我想要的只是使该代码成为具有固定线程数的多线程。

for (ExampleType ex : exampleData) {
    exampleFunction(ex.getSomeData());
}

我尝试过但没有成功,从谷歌找到了它

final ExecutorService testExecutor = Executors.newFixedThreadPool(10); // just 10 thread
final List<Future<?>> executeDatas = new ArrayList<List>();

for (ExampleType ex : exampleData) {
    Future<?> executeData = testExecutor.submit(() -> {
        exampleFunction(ex.getSomeData());
    });
    executeDatas.add(executeData);
}

for (Future<?> executeData : executeDatas) {
    executeData.done(); // do i need to write stuff here? i don't have done() function
}

它可能会起作用,但表示 -source 1.6 不支持钻石运算符。是的,我不知道如何从这里处理并被卡住了。感谢任何帮助

最佳答案

由于某种原因,没有人显示转换后的代码,所以我会这样做:

final ExecutorService testExecutor = Executors.newFixedThreadPool(10);
final List<Future<?>> executeDatas = new ArrayList<Future<?>>();

for (ExampleType ex : exampleData) {
    Future<?> executeData = testExecutor.submit(new Runnable() {
        @Override
        public void run() {
            exampleFunction(ex.getSomeData());
        }
    });
    executeDatas.add(executeData);
}

for (Future<?> executeData : executeDatas) {
    // calling get in loop to effectively wait for all the futures to finish
    executeData.get();
}

进行了三项更改:

  1. ArrayList<List>替换为 ArrayList<Future<?>>
  2. Lambda 替换为匿名类实例化
  3. .done()更改为.get()等待所有 future 执行完毕

关于java - 在 Java 1.6 中使用 For 循环和多线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50049810/

相关文章:

java - 添加 Enter 键作为 JButton 加速器

Java Web 服务器应用程序

java - GPS 坐标未正确存储在从 android 到 php 的数据库中

java - 多边形在旋转时移动

c# - 等待一个或多个任务达到某个里程碑,即异步/等待方式

multithreading - 启 Action 业错误 : The term <NAME> is not recognized as the name of a cmdlet, 函数、脚本文件或可运行程序

java - 如何从对话框内的edittext获取文本

java - 寻找在多线程平台上创建用户名的好方法

android 应用程序在 webview url 更改时崩溃

python - python pool.map 中的多线程引发 TypeError : object of type 'float' has no len()