Java 取消BufferedReader';s readLine()
我写了一个无休止的循环,我想每5秒发送一条用户消息。因此,我编写了一个线程,等待5秒钟,然后发送readLine()方法接收到的消息。如果用户没有提供任何输入,则由于readLine()方法等待输入,循环不会继续。那么如何取消readLine()方法呢Java 取消BufferedReader';s readLine(),java,bufferedreader,readline,Java,Bufferedreader,Readline,我写了一个无休止的循环,我想每5秒发送一条用户消息。因此,我编写了一个线程,等待5秒钟,然后发送readLine()方法接收到的消息。如果用户没有提供任何输入,则由于readLine()方法等待输入,循环不会继续。那么如何取消readLine()方法呢 while(true){ 新线程(){ @凌驾 公开募捐{ 试一试{ long startTime=System.currentTimeMillis(); 而((System.currentTimeMillis()-startTime)代码>,例
while(true){
新线程(){
@凌驾
公开募捐{
试一试{
long startTime=System.currentTimeMillis();
而((System.currentTimeMillis()-startTime)<5000){
}
toClient.println(serverMessage);
clientMessage=fromClient.readLine();
System.out.println(clientName+“:”+clientMessage);
}捕获(IOE异常){
e、 printStackTrace();
}
}
}.start();
serverMessage=input.readLine();
}
这看起来是生产者-消费者类型的问题,我会完全不同地构造它,因为这是来自client.readLine()的代码>被阻塞,因此应该在另一个线程中执行
考虑将另一线程中的用户输入读入数据结构、<代码>队列>代码>,例如<代码> LinkedBlockingQueue < /代码>,然后在每隔5秒从代码中的队列中检索字符串元素,或者如果队列中没有元素,则什么也不做。
像
new Thread(() -> {
while (true) {
try {
blockingQueue.put(input.readLine());
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
try {
while (true) {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
String input = blockingQueue.poll();
input = input == null ? "" : input;
toClient.println(input);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();
旁注:不要在线程上调用.stop()
,因为这样做很危险。还要避免扩展线程。fromClient.readLine()不是问题所在。只有input.readLine()引起了我的问题,但我会试试你的建议。@Luke举个例子
new Thread(() -> {
while (true) {
try {
blockingQueue.put(input.readLine());
} catch (InterruptedException | IOException e) {
e.printStackTrace();
}
}
}).start();
new Thread(() -> {
try {
while (true) {
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
String input = blockingQueue.poll();
input = input == null ? "" : input;
toClient.println(input);
}
} catch (IOException e) {
e.printStackTrace();
}
}).start();