I have 2 threads – one is to receiving messages and second is both for receiving and sending.
PrintStream os = new PrintStream(sock.getOutputStream());
BufferedReader is = new BufferedReader(new InputStreamReader(sock.getInputStream()));
ServerThread server = new ServerThread(sock, maxid, os,is);
OutputThread out = new OutputThread(sock, maxid, os,is);
Then, when I close connection I want to close is and os properly, but how to do it both in 2 threads? I get java.net.SocketException in ServerThread
public ServerThread(..){
try{
//here I use is and os
} finally {
disconnect();
}
}
public void disconnect() {
try {
System.out.println(addr.getHostName()+ " disconnected");
os.close();
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} finally {
this.interrupt();
}
}
Your threads are recieving the is and os from external sources and hence the responsibility of closing the streams should lie with the external entity. Do not close them inside the threads. Handle it externally in the place where they are created.