简体   繁体   English

在Java 1.6中将For循环与多线程一起使用

[英]Using For loop with Multi-threading in Java 1.6

I'm trying to use For loop with multi-threading in Java 1.6. 我试图在Java 1.6中将For循环与多线程一起使用。 I tried to use streams but apparently it was added in Java 1.8, so i tried to useExecutorService and Future but i can't make it work. 我尝试使用流,但是显然它是在Java 1.8中添加的,因此我尝试使用ExecutorService和Future,但无法使其正常工作。

What i want is just make this code multi-threaded with fixed number of threads. 我想要的只是使此代码具有固定线程数的多线程。

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

What i tried and didn't work, found it somewhere from google 我尝试但没有奏效的东西,是在Google某处找到的

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
}

It probably would've worked but says diamond operator is not supported in -source 1.6. 它可能会起作用,但是说-source 1.6不支持Diamond运算符。 Yeah i'm not sure how to handle from here and been stuck. 是的,我不确定如何从这里处理并被卡住。 Any help is appreciated 任何帮助表示赞赏

For some reason, noone shows the transformed code, so I'll do it: 由于某种原因,没有人显示转换后的代码,因此我将这样做:

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();
}

Three changes are made: 进行了三个更改:

  1. ArrayList<List> replaced with with ArrayList<Future<?>> ArrayList<List>替换为ArrayList<Future<?>>
  2. Lambda replaced with anonymous class instantiation Lambda替换为匿名类实例化
  3. .done() changed to .get() to wait for all the futures to finish execution .done()更改为.get()以等待所有期货完成执行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM