代码之家  ›  专栏  ›  技术社区  ›  Yoshua Nahar

如何从ScheduledExecutorService获取数据

  •  0
  • Yoshua Nahar  · 技术社区  · 7 年前

    ScheduledExecutorService

    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();
      }
    
    }
    

    :

    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;
      }
    
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   OldCurmudgeon    7 年前

    我会 Camera BlockingQueue -可能因此成为 MovieCamera

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

    然后,您可以为队列提供数据,而不仅仅是存储图片。

    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.");
        }
    
    }