Reputation: 2489
I created a console chatapplication, that waits for user input with bufferedreader.readline() and should print chat messages from the partner simultaneously. But after readline() was invoked, no output is possible.
Waiting for messages and Sending Messages is realized in different threads.
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();
}
}
}
console
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;
}
}
Upvotes: 0
Views: 360
Reputation: 6718
Calling run()
doesn't start a new thread, it just executes the method. You need to create a new Thread
:
Runnable runnable = ...
Thread thread = new Thread(runnable);
thread.start() // <-- actually causes the run()
method to be executed asynchronously
Better still would be to use an ExecutorService
:
ExecutorService executor = ... executor.execute(runnable);
As these offer pooling of threads (amongst other features).
Upvotes: 1