Rae*_*mir 7 java concurrency multithreading
我有三个连接的线程,即第二个线程在第一个死后执行.
这是我的代码:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
如何使用ExecutorService而不是三个线程对象来实现此功能?
Lui*_*oza 22
如果您想要/需要的是一个接一个地执行一组作业,但是在与主应用程序线程不同的单个线程中,则使用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();
Run Code Online (Sandbox Code Playgroud)
您可以使用SingleThread ExecutorService和future.get()方法来控制线程的顺序执行。
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;
}
}
Run Code Online (Sandbox Code Playgroud)
顺序执行类
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();
}
}
Run Code Online (Sandbox Code Playgroud)
输出量
excuting task... Task Id: 1
excuting task... Task Id: 2
excuting task... Task Id: 3
Run Code Online (Sandbox Code Playgroud)
输出将始终相同,并且所有任务将按顺序执行。
| 归档时间: |
|
| 查看次数: |
14135 次 |
| 最近记录: |