future java get_Java Future:试图理解.get()方法时出现问题

这个Java程序设计了一个读取用户输入的场景,使用了ExecutorService和Future来实现5秒的超时功能。当用户在5秒内未输入任何内容,程序将显示为空。然而,实际运行中,即使用户在第二次输入时提供了数据,程序仍然会等待5秒并显示为空。问题在于超时逻辑未能正确处理连续输入的情况。
摘要由CSDN通过智能技术生成

import java.io.*;

import java.util.concurrent.*;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.Callable;

class _TimeOut_ extends PrintIn_Delays {

public static void main(String[] args)

throws InterruptedException {

TimeWait Timeout = new TimeWait();

String input = Timeout.readLine();

String input2 = Timeout.readLine();

}

}

class Reader implements Callable {

public String call() throws IOException {

BufferedReader br = new BufferedReader(

new InputStreamReader(System.in));

String input;

do {

input = br.readLine();

}while ("".equals(input));

return input;

}

}

class TimeWait extends _TimeOut_ {

public String readLine() throws InterruptedException {

ExecutorService ex = Executors.newSingleThreadExecutor();

String input = null;

try {

try {

Future result = ex.submit(

new Reader());

input = result.get(5, TimeUnit.SECONDS);

} catch (ExecutionException e) {

e.getCause().printStackTrace();

} catch (TimeoutException e){}

} finally {

ex.shutdownNow();

}

System.out.println(" "+input);

return input;

}

}

这将等待用户输入5秒。如果用户不输入任何内容,则显示为空。

现在的问题是:

当我运行它时,它会等待5秒等待我的输入,但我没有输入任何内容,因此输出为空。然后在第二个输入中,输入“hi”。但它仍然会等待5秒(这不应该),在接受输入之后,它仍然显示为空。输出如下:

null

hi

null

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值