Java – run runnable multiple times in completable future
•
Java
I want to execute multiple threads, which will try to add to my custom list mylist at the same time, but I can't see any output when I try to count
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:
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())); } } }
class 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; } }
Follow up questions:
The countdownlatch program does not end The number of sysouts is 10001, and the last output is in runnable: 9: pool-1-thread-1
Countdownlatch implementation:
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(); } }
Solution
You call completabilefuture. You do not use the executor you created runAsync(Runnable runnable).
CompletableFuture.runAsync(new MyRunner<String>(list),threadPool);
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码