Skip to content

Instantly share code, notes, and snippets.

@atomAltera
Created January 23, 2014 12:31
Show Gist options
  • Save atomAltera/8577776 to your computer and use it in GitHub Desktop.
Save atomAltera/8577776 to your computer and use it in GitHub Desktop.
Simple Java example of using Executor Services
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class T_ExecutorService {
public static void main(String[] args) throws InterruptedException {
ExecutorService ex = Executors.newFixedThreadPool(20);
System.out.printf("! Creating Executing service: %s%n", ex.getClass().getName());
System.out.println("! Submitting tasks");
List<Future<Integer>> results = new ArrayList<>();
for (int i = 0; i < 10; i++) {
results.add(ex.submit(new FooTask(i)));
Thread.sleep(ThreadLocalRandom.current().nextInt(100));
}
System.out.println("! Tast submitting done");
while (results.size() > 0) {
Future<Integer> remove_candidate = null;
for (Future<Integer> result : results) {
if (result.isDone()) {
try {
System.out.printf("Got result: %d%n", result.get());
remove_candidate = result;
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
if (remove_candidate != null) results.remove(remove_candidate);
Thread.sleep(100);
}
System.out.println("! All task finished");
ex.shutdown();
}
}
class FooTask implements Callable<Integer> {
int tmp = 0;
int bar = 0;
ThreadLocalRandom random;
public FooTask(int bar) {
this.bar = bar;
this.random = ThreadLocalRandom.current();
System.out.printf("+ Created task: %d%n", this.bar);
}
@Override
public Integer call() throws Exception {
for (; ; ) {
this.tmp++;
// System.out.printf("\t\tThread: \t#%d \t\t%d%n", this.bar, this.tmp);
if (random.nextInt(100) == 0) {
System.out.printf("- Thread: %d completted%n", this.bar);
return tmp;
}
Thread.sleep(random.nextInt(100));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment