gpt4 book ai didi

java - 在 CompletableFuture 中多次运行 Runnable

转载 作者:行者123 更新时间:2023-12-04 22:48:27 26 4
gpt4 key购买 nike

我想执行多个线程,这些线程将尝试同时添加到我的自定义列表 MyList ,但是当我尝试计数时没有看到任何输出

    public static void main(String[] args) {

MyList<String> list = new list<String>();

MyRunner<String> myRunner = new MyRunner<String>(list);

ExecutorService threadPool = Executors.newFixedThreadPool(4);

for(int i = 0; i < 20; i++) {
CompletableFuture.runAsync(new MyRunner<String>(list));
}

try {
threadPool.awaitTermination(100l, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println(list.getCount());
}

运行类:
class MyRunner<String> implements Runnable {

MyList<String> list;

public MyRunner(MyList <String> t) {
this.list = t;
}

@Override
public void run() {
for(int i = 0; i < 200; i++) {
list((String) (i + Thread.currentThread().getName()));
}

}
}

类 MyList :
public class MyList<T> {

Queue<T> blockingQueue;
Lock lock;

long count;

public MyList() {
blockingQueue = new LinkedList<>();
count = 0;
lock = new ReentrantLock();
}

public void add(T singleTon) {
lock.lock();
blockingQueue.offer(singleTon);
count +=1;
lock.unlock();
}

public long getCount() {
return count;
}


}

跟进问题:

使用 CountDownLatch该计划并没有结束。 sysout 的数量为 10001,最后输出为 In runnable: 9 : pool-1-thread-1 CountDownLatch执行 :
public static void main(String[] args) throws InterruptedException {

MyList<String> mylist = new MyList<>();

CountDownLatch latch = new CountDownLatch(10);

ExecutorService executorService = Executors.newFixedThreadPool(4);


for(int i = 0; i < 1000; i++) {
CompletableFuture.runAsync(new MyRunner<String>(mylist, latch), executorService);
}

latch.await();

System.out.println(mylist.count);
}


class MyRunner<String> implements Runnable {

MyList<String> mylist;
CountDownLatch latch;

public MyRunner(MyList<String> mylist, CountDownLatch latch) {
this.latch = latch;
this.mylist = mylist;
}

@Override
public void run() {
for(int i = 0; i < 10; i++) {
System.out.println("In runnable: "+ i + " : "+ Thread.currentThread().getName());
mylist.add((String)("" + i));
}

latch.countDown();
}
}

最佳答案

您调用 CompletableFuture.runAsync(Runnable runnable)不使用 Executor你创造的。
改用 CompletableFuture.runAsync(Runnable runnable, Executor executor)通过传递您的 Executor实例如:

CompletableFuture.runAsync(new MyRunner<String>(list), threadPool);

关于java - 在 CompletableFuture 中多次运行 Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51879801/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com