开发者

Java: alternative to sleep in loop?

开发者 https://www.devze.com 2023-01-20 04:57 出处:网络
I need to listen to a serial input continuously, but NetBeans warns \"Invoking Thread.sleep in loop can cause performance problems.\"

I need to listen to a serial input continuously, but NetBeans warns "Invoking Thread.sleep in loop can cause performance problems." I understand why this causes performance problems, but what is the best alternative in Java?

public class SerialIO extends javax.swing.JFrame {
    ...
    class RcvTask extends Thread {
        public void run() {
            try {
                SerInputStream sis = new SerInputStream(serialPort);
                InputStreamReader isr = new InputStreamReader(sis);
                BufferedReader reader = new BufferedReader(isr);
                while (true) {
                    String line = reader.readLine()开发者_StackOverflow社区;
                    parse(line);
                    sleep(RX_SLEEP);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    ...


Why do you need to sleep ?

BufferedReader.readLine() is a blocking operation.


On the same topic :

  • Java BufferedReader readline blocking?
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号