我想要执行多个线程,这些线程将尝试同时添加到我的自定义列表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());
}
Runner类:
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();
}
}
答案 0 :(得分:6)
您调用的CompletableFuture.runAsync(Runnable runnable)
不使用您创建的Executor
。
通过传递CompletableFuture.runAsync(Runnable runnable, Executor executor)
实例(例如:
Executor
CompletableFuture.runAsync(new MyRunner<String>(list), threadPool);