Skip to content

Instantly share code, notes, and snippets.

@ericdcobb
Created August 22, 2014 15:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ericdcobb/46b817b384f5ca9d5f5d to your computer and use it in GitHub Desktop.
Save ericdcobb/46b817b384f5ca9d5f5d to your computer and use it in GitHub Desktop.
'CachedThreadPool' type behavior with a max number of threads.
package com.levelsbeyond;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Thread Test
*/
public class App
{
public static void main(String[] args) throws InterruptedException {
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 5,
10L, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>());
executor.allowCoreThreadTimeOut(true);
runTasks(executor);
System.out.println("Sleeping");
Thread.sleep(15000);
runTasks(executor);
}
private static void runTasks(ThreadPoolExecutor executor) {
for (int i = 0; i < 10; i++) {
executor.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
System.out.println(String.format("Thread: %s, Time: %s", Thread.currentThread().getName(),
new Date().toString()));
return null;
}
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment