【发布时间】:2017-09-22 01:13:25
【问题描述】:
我正在创建一个单线程 ExecutorService,并将需要异步执行的任务 (CompletableFuture) 分配给该单线程服务(同时尝试了 runAsync 和 supplyAsync)。
package Executor;
import java.util.Date;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ExecutorResolver {
ExecutorService es = Executors.newSingleThreadExecutor();
volatile int counter = 2;
static int ten = 10;
static int five = 5;
public void printer() {
System.out.println("This thread is complete :" + Thread.currentThread().getName());
System.out.println(new Date(System.currentTimeMillis()));
}
public void execute() {
CompletableFuture<Void> ct = CompletableFuture.allOf(CompletableFuture.runAsync(() -> {
try {
Thread t = new Thread();
Thread.sleep(ten * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, es).thenRunAsync(this::printer), CompletableFuture.runAsync(() -> {
try {
Thread t = new Thread();
Thread.sleep(five * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}, es).thenRunAsync(this::printer)
);
}
public static void main(String args[]) {
ExecutorResolver er = new ExecutorResolver();
er.execute();
for (int i = 0; i < 1000; i++) {
System.out.println("Current thread name : " + Thread.currentThread().getName() + i);
}
System.out.println(new Date(System.currentTimeMillis()));
}
}
但是它们是同步执行的,
请让我知道这是可能的还是我做错了什么?
【问题讨论】:
-
如果你只有一个线程,你想如何并行运行两段不同的代码?
-
这些
Thread t = new Thread();行无效。新构建的线程没有要执行的相关操作,并且无论如何都不会启动。您对这些线路有何期待? -
@SpiderPig :我不希望它们并行运行,将它们视为 Web 服务调用,只是希望这两个活动的返回时间不同,比如第一个启动的活动,有 10秒睡眠,应在第二秒后返回,睡眠 5 秒。
-
@Holger:先生,可能是它们没有效果,可能是我遗漏了某些部分,我只想
-
首先,正如已经说过的,在某处写
Thread t = new Thread();根本没有任何效果。其次,你的“异步”作业由指定的executor执行,这就是executor的含义,顾名思义。没有“唤醒执行者服务”这样的事情。由于执行器是单线程的,因此作业是单线程执行的,一个接一个。第三,不,完整的未来无法通过调用sleep神奇地发现您正在浪费线程。你有一个线程,你让那个线程休眠。一个正在睡觉的线程在睡觉,没有别的。
标签: multithreading asynchronous java-8 executorservice completable-future