取消BufferedReader的readLine()

问题描述 投票:0回答:1

我写了一个无限循环,我想每隔5秒发送一次用户消息。因此,我编写了一个等待5秒的线程,然后发送readLine()方法接收的消息。如果用户没有给出任何输入,则由于readLine()方法等待输入,循环不会继续。那么如何取消readLine()方法呢?

while (true) {
        new Thread() {
            @Override
            public void run() {
                try {
                    long startTime = System.currentTimeMillis();
                    while ((System.currentTimeMillis() - startTime) < 5000) {
                    }
                    toClient.println(serverMessage);
                    clientMessage = fromClient.readLine();

                    System.out.println(clientName + ": " + clientMessage);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        serverMessage = input.readLine();
    }
java bufferedreader readline
1个回答
1
投票

这看起来是生产者 - 消费者类型问题,我将完全不同地构造它,因为这个fromClient.readLine();是阻塞的,因此应该在另一个线程中执行。

因此,请考虑将另一个线程中的用户输入读入数据结构,Queue<String>(例如LinkedBlockingQueue<String>),然后每隔5秒从代码中的队列中检索String元素,如果队列中没有元素,则不执行任何操作。

就像是....

new Thread(() -> {
    while (true) {
        try {
            blockingQueue.put(input.readLine());
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        }
    }
}).start();

 new Thread(() -> {
    try {
        while (true) {
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String input = blockingQueue.poll();
            input = input == null ? "" : input;
            toClient.println(input);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

}).start();

附注:不要在线程上调用.stop(),因为这是一件危险的事情。还要避免扩展Thread。

© www.soinside.com 2019 - 2024. All rights reserved.