gpt4 book ai didi

java - BufferedReader.readline() 阻止输出

转载 作者:行者123 更新时间:2023-12-01 13:02:05 25 4
gpt4 key购买 nike

我创建了一个控制台聊天应用程序,它等待用户使用 bufferedreader.readline() 输入,并且应该同时打印来自合作伙伴的聊天消息。但调用 readline() 后,无法输出任何内容。

等待消息和发送消息是在不同的线程中实现的。

public class MsgReader implements Runnable {

private Socket connection;
private final Console con;

public MsgReader(Socket sock, Console con) {
this.connection = sock;

this.con = con;
this.run();
}

@Override
public void run() {

InputStream is = null;
try {
is = connection.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

BufferedReader in = new BufferedReader(new InputStreamReader(is));
try {
System.out.println("asdf");
while (true) {

String ss = in.readLine();
// System.out.println((char)in.read());
// System.out.println("asdf");
//
con.write(ss);
// con.write(ss);

Thread.sleep(500);

}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}





public class MsgWriter implements Runnable {

private Socket connection;
private final Console con;

public MsgWriter(Socket sock, Console con) {
this.connection = sock;
this.con = con;

this.run();
}

@Override
public void run() {

OutputStream os = null;
try {
os = connection.getOutputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

OutputStreamWriter osw = new OutputStreamWriter(os);
BufferedWriter bw = new BufferedWriter(osw);
try {
char in = ' ';
boolean running = true;


while (true) {
String ss=In.inString2("");

if(ss.equals("")){
System.out.println("enter your message: ");
//String s = con.readLine();

String s=In.inString2("");

bw.write(s+"\n");
bw.flush();

System.out.println("sent");


}

if(ss.equals("x")){
break;
}
Thread.sleep(500);




}

} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("fail ");

e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

控制台

import inout.In;

public class Console {

public Console() {

}

public synchronized void write(String txt) {
System.out.println(txt);
}

public synchronized String readLine() {

String temp=In.inString2("");

return temp;
}
}

最佳答案

调用run()不会启动新线程,它只是执行该方法。您需要创建一个新的线程:

可运行可运行 = ... Thread 线程 = new Thread(可运行); thread.start()//<-- 实际上导致 run() 方法异步执行

更好的是使用 ExecutorService :

ExecutorService 执行器 = ... executor.execute(可运行);

因为它们提供线程池(以及其他功能)。

关于java - BufferedReader.readline() 阻止输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23450400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com