Skip to content

Instantly share code, notes, and snippets.

@ansig
Created November 27, 2014 19:26
Show Gist options
  • Save ansig/498eb7faf308684b32a5 to your computer and use it in GitHub Desktop.
Save ansig/498eb7faf308684b32a5 to your computer and use it in GitHub Desktop.
A thread pool with the executor framework to execute tasks. Also demonstrates a simple timeout mechanism.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* A thread pool with the executor framework to execute tasks. Also demonstrates a simple timeout mechanism.
*/
public class ThreadPool {
private static final int NTHREADS = Runtime.getRuntime().availableProcessors();
private static final int TIMEOUT = 10;
public static void main(String[] args) {
System.out.printf("Number of threads: %d%n", NTHREADS);
ExecutorService pool = Executors.newFixedThreadPool(NTHREADS);
for (int i = 0; i < 500000; i++) {
pool.execute(new Worker(i));
}
pool.shutdown();
try {
if (!pool.awaitTermination(TIMEOUT, TimeUnit.SECONDS)) {
System.out.printf("Timed out, shutting down now!%n");
pool.shutdownNow();
}
} catch (InterruptedException ie) {
System.err.printf("Interrupted while waiting for termination%n");
System.exit(1);
}
System.out.printf("Done!");
}
}
class Worker implements Runnable {
private long num;
public Worker(long num) {
this.num = num;
}
@Override
public void run() {
System.out.printf("%s will sum: %d%n", Thread.currentThread().getName(), this.num);
long sum = 0;
for (long i = 1; i <= num; i++) {
sum += i;
}
System.out.printf("%s got sum: %d%n", Thread.currentThread().getName(), sum);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment