user2731063
user2731063

Reputation:

How to execute tasks in ExecutorService sequentially?

I have three threads that are joined, i.e. the second thread executes after the first dies.

This is the code I have:

public class Main {
    public static void main(String args[]) throws Exception {
        final Thread thrdA = new Thread(() -> System.out.println("Message 1"));
        final Thread thrdB = new Thread(() -> System.out.println("Message 2"));
        final Thread thrdC = new Thread(() -> System.out.println("Message 3"));

        thrdA.start();
        thrdA.join();
        thrdB.start();
        thrdB.join();
        thrdC.start();
        thrdC.join();

    }
}

How would I implement this functionality using ExecutorService instead of three thread objects?

Upvotes: 12

Views: 22844

Answers (3)

Alexei Kaigorodov
Alexei Kaigorodov

Reputation: 13525

If you already use a thread pool in your application, you can reuse it by means of zero-threaded proxy serial executor, without creating special single threaded thread pool. One implementation is described in the javadoc section of Executor interface, another, optimized implementation, at my Github repository CodeSamples.

Upvotes: 3

Amit Tamrakar
Amit Tamrakar

Reputation: 528

You can control sequential execution of threads using SingleThread ExecutorService with future.get() method.

DummyTask Class

import java.util.concurrent.Callable;

public class DummyTask implements Callable<Integer>
{

int taskId;

public DummyTask(int taskId) {
    this.taskId = taskId;
}

@Override
public Integer call() throws Exception
{
    System.out.println("excuting task... Task Id: " + taskId);
    return taskId;
}

}

SequentialExecution Class

package com.amit.executorservice;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class SequentialExecution 
{
public static void main(String[] args) throws InterruptedException, ExecutionException {

    DummyTask task1 = new DummyTask(1);
    DummyTask task2 = new DummyTask(2);
    DummyTask task3 = new DummyTask(3);
    Future<Integer> result = null;
    ExecutorService executor = Executors.newSingleThreadExecutor();

    result = executor.submit( task1 );
    // future.get() Waits for the task to complete, and then retrieves its result.
    result.get();

    result = executor.submit( task2 );
    // future.get() Waits for the task to complete, and then retrieves its result.
    result.get();

    result = executor.submit( task3 );
    // future.get() Waits for the task to complete, and then retrieves its result.
    result.get();

    executor.shutdown();

}
}

Output

excuting task... Task Id: 1
excuting task... Task Id: 2
excuting task... Task Id: 3

Output will always be same and all task will get executed in sequence.

Upvotes: 8

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

If what you want/need is to execute a group of jobs one after another but in a single thread different that the main app thread, then use Executors#newSingleThreadExecutor.

ExecutorService es = Executors.newSingleThreadExecutor();
es.submit(() -> System.out.println("Message 1"));
es.submit(() -> System.out.println("Message 2"));
es.submit(() -> System.out.println("Message 3"));
es.shutdown();

Upvotes: 28

Related Questions