Hello to all!

There is such a question guys. There are three threads and a queue. One thread adds objects to the queue, the second and third, respectively, are taken.

The question is how best to implement a sample of objects from the queue. There are 2 options, which one is preferable in terms of multithreading?

The first:

// Класс, который реализует синхронизированную очередь public synchronized void add(Object o) { someQueue.add(o); } public synchronized Object get() { if(someQueue.size() == 0) return null; else return someQueue.remove(0); } // Класс, вынимающий объекты. Запущено два инстанса public void run() { while(True) { Object o = queue.get() if (o == null) { TimeUnit.SECONDS.sleep(1); continue; } ...... } 

Second:

 // Класс, который реализует синхронизированную очередь public synchronized void add(Object o) { someQueue.add(o); notifyAll(); } public synchronized Object get() { if(someQueue.size() == 0) return null; else return someQueue.remove(0); } // Класс, вынимающий объекты. Запущено два инстанса public void run() { while(True) { Object o = queue.get() if (o == null) { try { synchronized(queue) { queue.wait(1000); } } catch (Exception e) {} continue; } ...... } 

    2 answers 2

    So yes. You yourself answered. Use either ArrayBlockingQueue or LinkedBlockingQueue . Conditional Variable is completely useless. You can also use ExecutorService .

     private final LinkedBlockingQueue<String> myStrangeQueue = new LinkedBlockingQueue<String>(); public void add(String message) { myStrangeQueue.put(message); } public void run() { try { while (true) processMessage(myStrangeQueue.take()); } catch(InterrupedException ignore) { } } private void processMessage(String message) { // ... } 

      Third. Using Condition Variable .

      • Are you talking about ArrayBlockingQueue? - dude
      • I'm talking about await () + signal () instead of sleep (1) - Andrew Frolov
      • Sorry for the intrusiveness, is it possible to give an example by remaking my code? And then something, I think, you offer the same option 2, just a side view. - dude
      • And there is. wait + signal is the same as synchronized in this case. - cy6erGn0m