I'm trying to write an instant messaging program in Java. What I have coded so far, goes like this: Each client connects to a thread created by the server, to which he/she sends the message. My doubt is, how can I kill all the threads that have been created by the main program when the administrator presses de 'q' in the keyboard. I made a class for a thread whose only function is to read the 'q' from the keyboard, but, how can I notify to the main program that it must kill all the threads?
This is the Server (it is not complete):
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
boolean listening = true;
new StdinReaderThread();
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not create socket");
System.exit(-1);
}
while (listening){
new ServerThread(serverSocket.accept()).start();
}
serverSocket.close();
}
}
This is the thread which reads 'q' from keyboard:
public class StdinReaderThread implements Runnable{
BufferedReader stdin;
public StdinReaderThread(){
Thread subpr = new Thread(this,"x");
stdin = new BufferedReader( new InputStreamReader(System.in));
subpr.start();
}
public void run(){
while (true){
try{
String stdinline = stdin.readLine();
if( stdinline.startsWith("q")){
System.out.println("end");
}
else if( stdinline.startsWith("m"))
System.out.println("send message");
else if( stdinline.startsWith("l"))
System.out.println("send login");
else if( stdinline.startsWith("u"))
System.out.println("list users");
} catch (Exception e){}
}
}
}