Skip to content

Instantly share code, notes, and snippets.

@sshark
Last active October 6, 2017 12:47
Show Gist options
  • Save sshark/8932918 to your computer and use it in GitHub Desktop.
Save sshark/8932918 to your computer and use it in GitHub Desktop.
Java Future implementation example
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
*
* @author Lim, Teck Hooi
*
*
*/
public class RunMeFuture {
private static final int NTHREDS = 10;
private static int counter = 0;
private static Random rand = new Random();
public static void main(String[] args) throws Exception {
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < 40; i++) {
Callable<Integer> worker = new RunMeFutureCallable();
futures.add(executor.submit(worker));
}
for (Future<Integer> future : futures) {
System.out.println(future.get());
}
executor.shutdown();
}
static class RunMeFutureCallable implements Callable<Integer> {
@Override
public Integer call() throws Exception {
int i = counter;
Thread.sleep(rand.nextInt(1000));
counter = i + 1;
return counter;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment