Skip to content

Instantly share code, notes, and snippets.

@hitxiang
Forked from ericdcobb/threads.java
Last active August 29, 2015 14:18
Show Gist options
  • Save hitxiang/e77f5f82235168c228e9 to your computer and use it in GitHub Desktop.
Save hitxiang/e77f5f82235168c228e9 to your computer and use it in GitHub Desktop.
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;
}
});
}
}
}
@hitxiang
Copy link
Author

hitxiang commented Apr 2, 2015

Same with FixedThreadPool, except
executor.allowCoreThreadTimeOut(true);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment