私はマルチスレッドに精通していません。1つのプロデューサースレッドでスクリーンショットを繰り返し撮ろうとしています。これにより、BufferedImage
オブジェクトが追加されConcurrentLinkedQueue
、コンシューマースレッドがオブジェクトをpoll
キューにBufferedImage
入れてファイルに保存します。notify()
繰り返しポーリング(whileループ)することでそれらを消費することはできますが、とを使用してそれらを消費する方法がわかりません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()
。私は正しいことをしていますか?助けてください。ありがとう。