您可以使用 SingleThread ExecutorService 和 future.get() 方法控制线程的顺序执行。
虚拟任务类
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();
}
}
输出
excuting task... Task Id: 1
excuting task... Task Id: 2
excuting task... Task Id: 3
输出将始终相同,所有任务将按顺序执行。