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

别等时光非礼了梦想. 提交于 2019-12-01 13:22:58

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!