2021年3月17日星期三

Multi threaded java method exiting before it can complete [duplicate]

I have a method that creates a threadpool and uses a blocking queue. The queue contains some strings and elements form the queue are removed and a runnable action is submit to thread executor. This runnable action will extract info then add new elements in the queue. I have added a while loop around the queue but the method exists before new elements can be added to the queue.

   final BlockingQueue<String> myQueueOfStrings = new LinkedBlockingDeque<>(100);     private final Map <String, Set<String>> test;       public Map<String, String> multiThreadExample(){         final ExecutorService executorService = Executors.newFixedThreadPool(20);         myQueueOfStrings.put("Test String");              while(!myQueueOfStrings.isEmpty()) {               executorService.submit(() -> {                 try {                     extractSubStrings(myQueueOfStrings.take());                 } catch (InterruptedException e) {                     e.printStackTrace();                 }             });         }           return test;     }    private void extractSubStrings(String str){      test.put("new sub string", str.substring(0))      myQueueOfStrings.add( str.substring(0));  }  

I am assuming this is because elements gets removed from the queue and then the while loop exists straight away before the thread can add new elements to the queue. Does anyone have ideas about how to fix this problem or the best way to implement what I am trying to do here?

https://stackoverflow.com/questions/66683680/multi-threaded-java-method-exiting-before-it-can-complete March 18, 2021 at 09:50AM

没有评论:

发表评论