[英]High CPU usage when reading from console
So i am writing a little program that takes user input 所以我正在编写一个需要用户输入的小程序
public class Test {
public static void main(String[] args) throws IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
String something = input.readLine();
}
}
Here is the relavent section cut out, I run this and the main thread blocks on readline() but my CPU usage is ~15-20% consistently. 这是删掉的relavent部分,我在readline()上运行了此线程和主线程块,但是我的CPU使用率始终保持在15-20%。
What is up here, is there a more efficient way to read from the console. 这里提供的是从控制台读取的更有效方法。
EDIT: I am on Mac OS 10.8 and the process has been running for 20 minutes now. 编辑:我在Mac OS 10.8上,该进程现在已经运行了20分钟。 The input.readline() statement is wrapped in a while true loop with some simple processing inside but i know the code is not getting there.
input.readline()语句包装在一个true循环中,内部进行了一些简单处理,但是我知道代码没有到达那里。
I assume you have some kind of code that checks the status of readLine(), otherwise Java will continue to block. 我假设您有某种代码可以检查readLine()的状态,否则Java将继续阻塞。
String line = null;
while ((line = br.readLine()) != null) {
// handle contents of line here
}
You may be better off using the Scanner class to read user input. 使用Scanner类读取用户输入可能会更好。
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.