Executor interface in java.util.concurrent package lets you submit Runnable tasks. Executor then handles the execution of the task. This interface provides a way of decoupling task submission from the mechanics of how each task will be run, including details of thread use, scheduling, etc.

Contract of Executor interface has a single method: execute(Runnable command)

The following executor is one of basic implementations. It creates a new thread for each Runnable task.

public class ThreadPerTaskExecutor implements Executor {

    public static void main(String[] args) {
        Executor executor = new ThreadPerTaskExecutor();
        executor.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println("Task completed!");
            }
        });
    }

    @Override
    public void execute(Runnable command) {
        new Thread(command).start();
    }
}

 

Leave a Reply

Close Menu