简体   繁体   中英

Using For loop with Multi-threading in Java 1.6

I'm trying to use For loop with multi-threading in Java 1.6. 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.

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

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. 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<?>>
  2. Lambda replaced with anonymous class instantiation
  3. .done() changed to .get() to wait for all the futures to finish execution

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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