简体   繁体   English

取消BufferedReader的readLine()

[英]Cancel BufferedReader's readLine()

I've written an endless loop in which I want to send a User Message every 5 seconds. 我写了一个无限循环,我想每5秒发送一次用户消息。 Therefore I wrote a thread which waits for 5 seconds and then sends the Message received by the readLine() Method. 因此,我编写了一个线程,等待5秒钟,然后发送readLine()方法接收到的消息。 If the user doesn't give any input the loop doesn't go on because of the readLine() Method waiting for input. 如果用户不提供任何输入,则由于readLine()方法正在等待输入,因此循环不会继续进行。 So how can I cancel the readLine() Method? 那么,如何取消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();
    }

This looks to be a producer-consumer type problem and I would structure this entirely differently since this fromClient.readLine(); 这似乎是生产者-消费者类型的问题,由于fromClient.readLine(); ,我将以完全不同的方式构造此问题fromClient.readLine(); is blocking and thus should be performed within another thread. 正在阻塞,因此应在另一个线程中执行。

So consider reading the user input in another thread into a data structure, a Queue<String> such as a LinkedBlockingQueue<String> , and then retrieve String elements from the queue in the code above every 5 seconds, or nothing if no elements are held in the queue. 因此,请考虑将另一个线程中的用户输入读入数据结构(如LinkedBlockingQueue<String>Queue<String> ,然后每隔5秒从代码中的队列中检索String元素,如果不保留任何元素,则不进行任何操作在队列中。

Something like.... 就像是....

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

Side notes: don't call .stop() on a thread as that is a dangerous thing to do. 注意事项:不要在线程上调用.stop() ,因为这样做很危险。 Also avoid extending Thread. 同时避免扩展Thread。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM