【问题标题】:Cancel BufferedReader's readLine()取消 BufferedReader 的 readLine()
【发布时间】:2019-02-15 13:38:51
【问题描述】:

我编写了一个无限循环,我想在其中每 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】:

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

    所以考虑将另一个线程中的用户输入读入一个数据结构,一个Queue&lt;String&gt;比如LinkedBlockingQueue&lt;String&gt;,然后每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(),因为这样做很危险。还要避免扩展线程。

    【讨论】:

    • fromClient.readLine() 不是问题。只有 input.readLine() 会导致我的问题,但我会尝试你的建议。
    • @Luke 例如
    猜你喜欢
    • 2013-03-09
    • 2016-01-08
    • 2014-09-26
    • 2012-09-30
    • 2015-06-07
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多