Wednesday, August 12, 2015

Thread with ExecutorService

ThreadFactory buildCache = new ThreadFactoryBuilder().setNameFormat("thread-name-%d").build();
ExecutorService executorService = Executors.newFixedThreadPool(totalThreads, buildCache);

List<Future> trackingTask = new ArrayList<Future>();

for (int index = 0; index < totalThreads; index++) {
        trackingTask.add(executorService.submit(new Runnable() {
              @Override
               public void run() {
                      //run your code
               }
        }));
}

// Run and waiting for task to finish
for (Future task : trackingTask) {
        task.get();
}

// Shutdown executor:
executorService.shutdownNow();

No comments:

Post a Comment