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; } ...... }