I am writing a server in Java, which is multithreaded. I have three main active threads that I build and start from my main method:
public class Run{
public static void main(String[] args){
try{
/*
* Definition and initialization of "server," "time," and
* "commands" variables not shown.
*/
new Thread(server).start();
new Thread(time).start();
new Thread(commands).start();
}catch(FileNotFoundException unfound){
/* Exception code not shown */
}catch(IOException ioe){
/* Exception code not shown */
}
}
}
My commands thread is used, for example, for stopping the server by have the input "q" into the console window. commands's run method is defined as so:
public void run(){
while(server.running.get()){
try{
String next = scan.nextLine();
if(next.equalsIgnoreCase("q")){
server.shutdown();
close();
}else
System.out.println(LocalDateTime.now() + " - Unknown command.");
}catch(IOException ioe){
System.out.println(LocalDateTime.now() + " - The commands thread has produced an exception.");
}
}
}
*Where scan is defined as: Scanner scan = new Scanner(System.in);
When I run my server all my threads work, except the commands thread as the console is not accepting inputs.
I then realized, if I waited for my server thread (this is the thread I most care about) to join up with my main (static method) thread, my commands thread then worked. Meaning the console accepted inputs if I changed my main method code to this:
Thread t1 = new Thread(server);
t1.start();
new Thread(time).start();
new Thread(commands).start();
try{
t1.join();
}catch(Exception e){
e.printStackTrace();
}
Now to my question. Why does console input only work if the main thread is still active? I honestly do not need my main thread anymore, so letting it terminate would be just fine.
Is there something I am doing incorrectly here with just defining my threads without a name? I am able to terminate each thread nicely as they are interweaved with each other and everything works just except my commands thread.
EDIT: I really appreciate all of the answers regarding a fix to this issue but what I am really after is the reason of why this is happening.
The server thread spirals off and does it own thing (i.e. constantly looking for new connections and establishing new environments for those connections) and the renewal thread goes off and does its own thing as well (i.e. this is used for renewing my quota count as I am using a google API). Other than that, the above code gets the point across on what I am doing.