我创建了一个控制台chatapplication,它等待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;
}
}
答案 0 :(得分:1)
调用run()
并不启动新线程,只执行该方法。您需要创建一个新的Thread
:
Runnable runnable = ...
Thread thread = new Thread(runnable);
thread.start()//< - 实际上导致run()
方法异步执行
最好还是使用ExecutorService
:
ExecutorService executor = ... executor.execute(可运行);
因为这些提供了线程池(以及其他功能)。