How to check Scanner.hasNext(System.in) with a timeout if nothing is typed?

后端 未结 1 1719
不思量自难忘°
不思量自难忘° 2021-01-16 08:19
Scanner sc = new Scanner(System.in);

Scanner can be used for reading text files, user input streams, and more. I am specifically using it for readi

相关标签:
1条回答
  • 2021-01-16 09:06

    I see nothing wrong with having a Producer - Consumer here:

    // Shared queue
    final Queue<String> messages = new ConcurrentLinkedQueue<>();
    
    // Non-blocking consumer
    ScheduledExecutorService ses = Executors.newSingleThreadScheduledExecutor();
    ses.scheduleAtFixedRate(new Runnable(){
        @Override
        public void run() {
            // non-blocking
            while((String message = messages.poll()) != null) {
                // do something
            }
        }
    }, 0, 10, TimeUnit.MILLISECONDS);
    
    // Blocking producer
    Scanner sc = new Scanner(System.in);
    while(sc.hasNext()) {
        messages.add(sc.next());
    }
    

    The consumer can then just do non-blocking on the shared Queue. Only the producer knows that it is filled as soon as a new message is read.

    0 讨论(0)
提交回复
热议问题