【发布时间】:2012-01-11 19:56:00
【问题描述】:
我并不精通多线程。我试图通过一个生产者线程重复截屏,它将BufferedImage 对象添加到ConcurrentLinkedQueue,消费者线程将poll 队列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 方法更改为synchronised 并尝试实现wait() 和notify()。我做得对吗?请帮忙。谢谢。
【问题讨论】:
标签: java concurrency wait notify java.util.concurrent