简体   繁体   中英

How to get data back from a ScheduledExecutorService

I have a simple example where I use a ScheduledExecutorService and run tasked delayed. I would like to know if this is a good way to the data back from my camera object.

public class App {

  private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
  private final Camera camera = new Camera();

  private Object lastPicture;

  public static void main(String[] args) {
    App app = new App();
    app.takePicture();

    // getLatestPicture when I need it on my frontend, in the future. (so image that this part can get called anytime).
    // I also want to check if this picture is not the same as the last. (I might call getLastPicture multiple times within the second.)
    Object currentPicture = app.getLastPicture();
    if (lastPicture == currentPicture) {
      System.out.println("Same picture");
    }
    System.out.println(currentPicture);
  }

  private void takePicture() {
    executorService
        .scheduleWithFixedDelay(takePictureTask(), 0, 1000, TimeUnit.MILLISECONDS);
  }

  private Runnable takePictureTask() {
    return () -> camera.takePicture();
  }

  public Object getLatestPicture() {
    return camera.getPicture();
  }

}

Camera :

public class Camera {

  private Object picture;

  public void takePicture() {
    System.out.println("Taking picture...");

    try {
      Thread.sleep(100);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    picture = new Object();

    System.out.println("Finished taking picture.");
  }

  public Object getPicture() {
    return picture;
  }

}

I would make Camera feed a BlockingQueue - probably therefore making it a MovieCamera .

    private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    private final BlockingQueue<Object> pictures = new ArrayBlockingQueue<>();
    private final Camera camera = new Camera(pictures);

You can then feed the queue rather than just storing the picture.

public static class Camera {
    private final BlockingQueue<Object> pictureQueue;

    public Camera(BlockingQueue<Object> pictureQueue) {
        this.pictureQueue = pictureQueue;
    }

    public void takePicture() {
        System.out.println("Taking picture...");

        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        pictureQueue.put(new Object());

        System.out.println("Finished taking picture.");
    }

}

And you have full flexibility in handling the queue. You can get the latest picture by polling the queue until it is empty and know if there have been more pictures automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM