Created
November 1, 2013 15:54
-
-
Save mzimecki/7267479 to your computer and use it in GitHub Desktop.
[Java] Callable, Future, Executors example
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 com.zimek.executors; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.concurrent.Callable; | |
import java.util.concurrent.ExecutionException; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.concurrent.Future; | |
/** | |
* If task implements {@link Callable} it may return its result. | |
* We may use {@link Runnable} which does not return task result. | |
*/ | |
class TaskWithResult implements Callable<String> { | |
int id; | |
public TaskWithResult(int id) { | |
this.id = id; | |
} | |
@Override | |
public String call() throws Exception { | |
return "Result of task id: " + id; | |
} | |
} | |
public class ExecutorsExample { | |
public static void main(String [] args) { | |
int availableProcessors = Runtime.getRuntime().availableProcessors(); | |
ExecutorService exec = Executors.newFixedThreadPool(availableProcessors); | |
List<Future<String>> results = new ArrayList<Future<String>>(); | |
for(int i = 0; i < 10; i++) { | |
results.add(exec.submit(new TaskWithResult(i))); | |
} | |
for(Future<String> fs: results) { | |
try { | |
System.out.println(fs.get()); //waits for the task to complete and gets result | |
} catch (InterruptedException | ExecutionException e) { | |
e.printStackTrace(); | |
} finally { | |
exec.shutdown(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment