See the documentation for java.util.concurrent.Executors . It should fit your needs. Here is a simple example of its use:
public class ExecutorServiceTest {
static ExecutorService threadPool = Executors.newCachedThreadPool();
public static void main(String[] args) throws Exception {
for(int i = 0; i < 10; i++) {
runSomeTaskInThreadPool();
}
threadPool.shutdown();
threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
}
private static void runSomeTaskInThreadPool() {
Future future = threadPool.submit(new Runnable() {
public void run() {
someTask();
}
});
}
static AtomicInteger counter = new AtomicInteger();
public static void someTask() {
System.out.println("someTask: " + counter.incrementAndGet()
+ " on thread: " + Thread.currentThread());
}
}
source
share