How to execute tasks in ExecutorService sequentially?

后端 未结 3 735
遇见更好的自我
遇见更好的自我 2020-12-10 14:38

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 s         


        
3条回答
  •  借酒劲吻你
    2020-12-10 15:30

    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
    {
    
    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 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.

提交回复
热议问题