简体   繁体   中英

Java: alternative to sleep in loop?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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