让你的主线程扮演执行者的角色:
static ArrayBlockingQueue<Runnable> queue = new ArrayBlockingQueue<>(10); public static void main(String... args) { // initialization... for (;;) { queue.take().run(); } }
每当您需要在主线程上执行任务时,将其放入队列:
queue.add(()->methodCall(1,2,3));
一个可能的解决方案 CompletableFuture :
CompletableFuture
class Job<T> { private final Supplier<T> computation; private final CompletableFuture<T> future; Job(Supplier<T> computation, CompletableFuture<T> future) { this.future = future; this.computation = computation; } public Supplier<T> getComputation() { return computation; } public CompletableFuture<T> getFuture() { return future; } } public void client() { // on the client: CompletableFuture<String> future = new CompletableFuture<>(); Supplier<String> computation = () -> "Here I am!"; enqueue(new Job<>(computation, future)); String resultString = future.get(); } public <T> void server(Job<T> job) { // on the server; job is taken from the queue CompletableFuture<T> future = job.getFuture(); future.complete(job.getComputation().get()); }
在这里,在客户端, future.get() 将无限期等待,直到结果可用。还有另一种形式:
future.get()
future.get(1, TimeUnit.MINUTES)
只会等待一分钟然后返回。这可用于轮询。
我不确定你是如何分时主线程的,但你所说的是你想要在主线程上依次使用多个线程和其他作业运行一些作业。
最简单的答案是使用两个不同的工作队列 - 一个由多个线程服务,另一个由主线程服务。
这将使两个队列更容易理解和使用。
此外,在任一队列上运行的作业都应实现一个接口,要求它们公开一个方法,该方法返回对结果数据的引用 - 这可能是实际结果,或者是附加到包含结果的文件的文件名或输入流。