1.

What is the ExecutorService interface?

Answer»

ExecutorService interface is basically a sub-interface of Executor interface with some additional methods or features that help in managing and controlling the execution of threads. It enables us to execute tasks asynchronously on threads.

Example: 

import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; public class TestThread { public static void MAIN(final String[] arguments) throws InterruptedException { ExecutorService e = Executors.newSingleThreadExecutor(); try { e.submit(new Thread()); System.out.println("SHUTDOWN executor"); e.shutdown(); e.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException ex) { System.err.println("tasks interrupted"); } finally { if (!e.isTerminated()) { System.err.println("cancel non-finished tasks"); } e.shutdownNow(); System.out.println("shutdown finished"); } } static class Task implements RUNNABLE { public void run() { try { Long DURATION = (long) (Math.random() * 20); System.out.println("Running Task!"); TimeUnit.SECONDS.sleep(duration); } catch (InterruptedException ex) { ex.printStackTrace(); } } } }

Output:

Shutdown executor shutdown finished


Discussion

No Comment Found