ConcurrentLinkedQueue с wait () и notify ()

Я плохо разбираюсь в многопоточности. Я пытаюсь сделать снимок экрана несколько раз одним потоком-производителем, который добавляет объект BufferedImage в ConcurrentLinkedQueue , а поток-потребитель будет опросить очередь для BufferedImage BufferedImage , чтобы сохранить их в файле. Я мог бы использовать их путем повторного опроса (цикл while), но я не знаю, как их использовать, используя notify () и wait () . Я пробовал использовать wait () и notify в небольших программах, но не смог реализовать это здесь.

У меня есть следующий код:

class StartPeriodicTask implements Runnable {
    public synchronized void run() {
        Robot robot = null;
        try {
            robot = new Robot();
        } catch (AWTException e1) {
            e1.printStackTrace();
        }
        Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit()
                .getScreenSize());
        BufferedImage image = robot.createScreenCapture(screenRect);
        if(null!=queue.peek()){
            try {
                System.out.println("Empty queue, so waiting....");
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            queue.add(image);
            notify();
        }
    }
}

public class ImageConsumer implements Runnable {
        @Override
        public synchronized void run() {
            while (true) {
                BufferedImage bufferedImage = null;
                if(null==queue.peek()){
                    try {
                        //Empty queue, so waiting....
                        wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else{
                    bufferedImage = queue.poll();
                    notify();
                }
                File imageFile = getFile();
                if (!imageFile.getParentFile().exists()) {
                    imageFile.getParentFile().mkdirs();
                }
                    try {
                        ImageIO.write(bufferedImage, extension, imageFile);
                        //Image saved
                    catch (IOException e) {
                        tracer.severe("IOException occurred. Image is not saved to file!");
                    }
                }
            }

Раньше у меня был повторный опрос для проверки существования объекта BufferedImage . Теперь я изменил метод run как synchronized и попытался реализовать wait () и notify () . Я правильно делаю? Пожалуйста помоги. Спасибо.

5
задан Ahamed 11 January 2012 в 19:56
поделиться