我有三个连接的线程,即第二个线程在第一个线程死亡后执行。
这是我的代码:
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();
}
}
如何使用
ExecutorService
而不是三个线程对象来实现此功能?
如果您想要/需要的是依次执行一组作业,但在与主应用程序线程不同的单个线程中,则使用
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();
您可以使用带有 future.get() 方法的 SingleThread ExecutorService 来控制线程的顺序执行。
DummyTask 类
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;
}
}
顺序执行类
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
输出将始终相同,所有任务将按顺序执行。
如果您的应用程序中已经使用了线程池,则可以通过零线程代理串行执行器的方式重用它,而无需创建特殊的单线程线程池。 Executor 接口的 javadoc 部分描述了一种实现,另一种优化实现位于我的 Github 存储库CodeSamples。