我正在尝试并行执行我的代码,但现在遇到了问题。 没有并行执行的代码正在等待输入(1),然后打印出一些东西(2)。 现在,我在计时器(任务2)的帮助下并行执行代码,对于输入(1),我得到了另一个循环。
现在,如果我尝试写下一些内容,但速度不够快,则输入不会读取整个输入,而整个输入会被任务2 的打印输出中断。
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static PrintStream out = new PrintStream(System.out);
static void test1(BufferedReader in, PrintStream out) throws IOException {
String input = in.readLine();
if (input.equals("test"))
System.out.println("true input");
else System.out.println("false input");
}
public static void main(String[] args) throws IOException {
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
while (true) {
System.out.println("print");
Thread.sleep(1000);}}}, 1000);
while (true)
test1(in, out);
}
最佳答案
您可以读取单个字符,直到按 Enter 键为止。
StringBuilder strBuilder = new StringBuilder();
char ch;
while((ch = in.read()) != '\n'){
strBuilder.append(ch);
}
String input = strBuilder.toString();
关于java - print 阻塞 BufferedReader 输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56170304/