我不是很精通多线程。我想通过一个生产者线程,它增加了BufferedImage
对象ConcurrentLinkedQueue
和消费者线程将poll
队列BufferedImage
对象保存它们在文件采取截图反复。我可以重复投票(while循环)消耗他们,但我不知道如何使用notify()
和wait()
消费它们。我已经尝试在较小的程序中使用wait()
和notify
,但在此处无法实现。的ConcurrentLinkedQueue与等待()和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
方法synchronised
,并试图实现wait()
和notify()
。我做得对吗?请帮忙。谢谢。
非常好!它的工作!非常感谢! – Ahamed 2012-01-11 20:25:28
单读者和单作者是什么意思?如果我们有多个线程提供和多个线程轮询会怎么样?那应该没问题吧? – Ahamed 2013-02-21 15:26:39
@Ahamed是的,但我的意思是这是一个1-1的关系。对于放入队列的每个线程,您需要从队列中进行相应的线程轮询。线程不能放置在SynchrnousQueue上并继续运行,必须有一个线程要求一个元素 - 此时线程可以继续。 – 2013-02-21 15:39:20