Created
December 21, 2016 14:29
-
-
Save nkcoder/7679cd897a3374c030c1027905704a70 to your computer and use it in GitHub Desktop.
CompletionService Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.nkcoder.module.javatest.concurrent; | |
import java.util.concurrent.*; | |
/** | |
* Created by nkcoder on 12/21/16. | |
*/ | |
public class CompletionServiceTest { | |
public static void main(String[] args) { | |
Executor executor = Executors.newFixedThreadPool(3); | |
CompletionService completionService = new ExecutorCompletionService(executor); | |
int size = 10; | |
for (int i = 0; i < size; i++) { | |
final int raw = i; | |
final int multiple = Math.multiplyExact(raw, raw); | |
completionService.submit(() -> { | |
System.out.println("raw = " + raw); | |
try { | |
TimeUnit.MILLISECONDS.sleep(multiple); | |
} catch (InterruptedException e) { | |
Thread.currentThread().interrupt(); | |
} | |
return multiple; | |
}); | |
} | |
for (int i = 0; i < size; i++) { | |
try { | |
Future future = completionService.take(); | |
System.out.println("multiple: " + future.get()); | |
} catch (InterruptedException | ExecutionException e) { | |
Thread.currentThread().interrupt(); | |
} | |
} | |
System.out.println("done."); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment