在同一线程上推送多个任务

时间:2018-08-25 11:31:39

标签: java multithreading threadpool

嗨,我正在尝试执行以下操作:

我在一侧有多个线程(例如A),在一侧有一个线程(例如B)。 A端的线程正在执行某些操作,并且通常需要向B线程提交一些任务。如何在Java中执行此操作?

我可以轻松地在A中创建多个线程,发现可以在B端安排任务,但每个任务都将由一个单独的线程运行。我希望它们全部由一个线程运行,以便可以按提交的顺序运行它们。

1 个答案:

答案 0 :(得分:0)

可以通过两个ExecutorSevice实例解决整个问题。

您根本不需要创建Thread。只需在一侧(A)放置fixed thread pool,然后在另一侧(B)将任务提交到single threaded

简单的例子:

public static void main(final String[] args) throws InterruptedException {

    final ExecutorService parallel = Executors.newFixedThreadPool(10);
    final ExecutorService single = Executors.newSingleThreadExecutor();

    final List<Callable<Void>> parallelTasks = IntStream.range(0, 10)
            .mapToObj(i -> (Callable<Void>) () -> {
                LockSupport.parkNanos(Duration.ofMillis(100).toNanos());
                System.out.printf("%s parallel %s%n", Thread.currentThread().getName(), i);
                single.submit(() -> {
                    System.out.printf("%s synchronous %s%n", Thread.currentThread().getName(), i);
                });
                return null;
            }).collect(toList());

    parallel.invokeAll(parallelTasks);
    parallel.shutdown();
    parallel.awaitTermination(1, TimeUnit.DAYS);
    single.shutdown();
    single.awaitTermination(1, TimeUnit.DAYS);
}

输出:

pool-1-thread-1 parallel 0  
pool-1-thread-4 parallel 3  
pool-1-thread-3 parallel 2  
pool-1-thread-2 parallel 1  
pool-1-thread-9 parallel 8  
pool-1-thread-6 parallel 5  
pool-1-thread-8 parallel 7  
pool-1-thread-7 parallel 6  
pool-1-thread-5 parallel 4
pool-2-thread-1 synchronous 3
pool-1-thread-10 parallel 9  
pool-2-thread-1 synchronous 1  
pool-2-thread-1 synchronous 8  
pool-2-thread-1 synchronous 2  
pool-2-thread-1 synchronous 5  
pool-2-thread-1 synchronous 7  
pool-2-thread-1 synchronous 0  
pool-2-thread-1 synchronous 6  
pool-2-thread-1 synchronous 4  
pool-2-thread-1 synchronous 9