本文介绍了通过CompletableFuture强制重用线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在严格使用:

  CompletableFuture 
.delayedExecutor(1,TimeUnit.MILLISECONDS).execute (()-> {});

从我在网上阅读的内容来看,通常每次通话都使用一个新线程。我想知道是否有一种方法可以重用线程而不是创建新线程?



更新



我不清楚-我想使用 CompletableFuture ,但我希望 CompletableFuture 重用某个线程,而不是管理自己的线程。



我看到这个问题:



,但是它建议使用环境变量-我想知道是否有一种方法可以通过编程方式做到这一点。

解决方案

执行器为每组任务创建新线程


I am making critical use of:

 CompletableFuture
  .delayedExecutor(1, TimeUnit.MILLISECONDS).execute(() -> {});

From what I have read online, it's common for this to use a new thread for every call. I am wondering if there is a way to re-use a thread instead of creating new threads?

Update:

I wasn't clear - I want to use CompletableFuture, but I want CompletableFuture to reuse a certain thread, instead of managing its own threads.

I see this question:CompletableFuture reuse thread from pool

but it recommends using an environment variable - I am wondering if there is a way to do this programmatically.

解决方案

Executor new Thread is created for every set of tasks

Executor executor = anExecutor;
executor.execute(new RunnableTask1());
executor.execute(new RunnableTask2());

So if you want to reuse the threads, create a thread pool by using ExecutorService or ThreadPoolExecutor, so one of the threads from the pool will execute the runnable tasks.

If all the threads are busy, tasks will be queued up to a certain limit and after that will get rejected through a RejectedExecutionException.

Example

public class NewMain {

    private static final ExecutorService ex = Executors.newFixedThreadPool(3);

    public static void main(String[] args) {
        Runnable r = () -> System.out.println(Thread.currentThread().getName());
        ex.execute(r);

        CompletableFuture<Void> c = CompletableFuture.runAsync(r, ex);
    }
}

Jdk-8 Use CompletableFuture.runAsync and pass runnable, Executor

public static CompletableFuture runAsync(Supplier supplier, Executor executor)

这篇关于通过CompletableFuture强制重用线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 20:28
查看更多