Ensuring task execution order in threadpool

后端 未结 17 1000
情深已故
情深已故 2020-12-12 11:54

I have been reading about the thread-pool pattern and I can\'t seem to find the usual solution for the following problem.

I sometimes want tasks to be executed serial

17条回答
  •  醉话见心
    2020-12-12 12:39

    Thread Pool with ordered and unordered execute methods:

    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class OrderedExecutor {
        private ExecutorService multiThreadExecutor;
        // for single Thread Executor
        private ThreadLocal threadLocal = new ThreadLocal<>();
    
        public OrderedExecutor(int nThreads) {
            this.multiThreadExecutor = Executors.newFixedThreadPool(nThreads);
        }
    
        public void executeUnordered(Runnable task) {
            multiThreadExecutor.submit(task);
        }
    
        public void executeOrdered(Runnable task) {
            multiThreadExecutor.submit(() -> {
                ExecutorService singleThreadExecutor = threadLocal.get();
                if (singleThreadExecutor == null) {
                    singleThreadExecutor = Executors.newSingleThreadExecutor();
                    threadLocal.set(singleThreadExecutor);
                }
                singleThreadExecutor.submit(task);
            });
        }
    
        public void clearThreadLocal() {
            threadLocal.remove();
        }
    
    }
    

    After filling all queues the threadLocal should be cleared. The only drawback is that singleThreadExecutor will be created each time the method

    executeOrdered(Runnable task)

    invoked in separate thread

提交回复
热议问题