【发布时间】:2019-04-09 21:27:24
【问题描述】:
我有RXTX串行通信示例的sn-p:
public static class SerialReader implements Runnable {
InputStream in;
public SerialReader(InputStream in) {
this.in = in;
}
public void run(){
byte[] buffer = new byte[1024];
int len = -1;
try {
while ((len = this.in.read(buffer)) > -1){
System.out.print(new String(buffer,0,len));
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
我想知道while 循环。根据我的理解,这种无休止的 while 循环对系统来说应该是过度的,应该避免。但是当我查看广告任务管理器时,我找不到显着的负载。
然后我改变while循环如下,系统过载。
while (true) {
System.out.print(new String(buffer,0,0));
}
为什么第一种方法不会产生高负载?我怎样才能使第二个周期不那么渴望 CPU?使用这样的算法是一种好习惯吗?
【问题讨论】:
-
“使用这样的算法是好的做法吗?”那要看。你想在你的循环中做什么?检查IO?如果是这样,轮询,因为它被称为 IO 有缺点。看看这个问题stackoverflow.com/questions/3072815/…
标签: java multithreading inputstream rxtx