ExecutorService which runs tasks in calling thread?

若如初见. 提交于 2019-12-30 22:55:52

问题


Are there any java.util.ExecutorService implementations which simply run all executed tasks in the calling thread? If this isn't included in Java by default, is there a library which contains an implementation like this?


回答1:


The only existing implementation I could find is SynchronousExecutorService - unfortunately buried somewhere in camel library.

Pasting source code (without comments) here for future reference:

package org.apache.camel.util.concurrent;

import java.util.List;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.TimeUnit;

public class SynchronousExecutorService extends AbstractExecutorService {

    private volatile boolean shutdown;

    public void shutdown() {
        shutdown = true;
    }

    public List<Runnable> shutdownNow() {
        return null;
    }

    public boolean isShutdown() {
        return shutdown;
    }

    public boolean isTerminated() {
        return shutdown;
    }

    public boolean awaitTermination(long time, TimeUnit unit) throws InterruptedException {
        return true;
    }

    public void execute(Runnable runnable) {
        runnable.run();
    }

}



回答2:


You may use Guava com.google.common.util.concurrent.MoreExecutors.sameThreadExecutor() which does exactly what you want: https://github.com/google/guava/blob/0434c5199c83c3f43b8b6a86c62e121d518fe7d0/guava/src/com/google/common/util/concurrent/MoreExecutors.java#L267

EDIT: The method has been renamed to com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService() https://github.com/google/guava/blob/f67ab864bde63fa6602b5688de0440957ffeaa2e/guava/src/com/google/common/util/concurrent/MoreExecutors.java#L369




回答3:


have you looked at java.util.concurrent.ThreadPoolExecutor?



来源:https://stackoverflow.com/questions/11941617/executorservice-which-runs-tasks-in-calling-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!