One socket and multiple threads
I'm trying to write a simple client that listens on a socket to perform certain tasks for other clients. Since one of functions takes longer to complete than the others, the rest of the quicker functions are rendered unavailable for that whole duration (if statements inside a while loop). As such, I thought it would be better to move the functions to separate threads: one thread to handle the time consuming function, and the second thread to other to handle the rest of the functions that only take milliseconds to complete.
The while loop that listens to the socket's input stream was moved to the thread's run() method, and the two threads are sequentially initialized in the main method with the code below.
Code:
new Thread(new longFunction(socket)).start();
new Thread(new quickFunctions(socket)).start();
Both threads are running and listening to the socket, but not at the same time. Only one thread listens at a time, meaning the functions that belong to the other thread are unavailable. How would I go about fixing this problem?
Edit: Below is the code used by both of the threads to listen to the socket. The listen() method is invoked in run() after the socket has been connected to the Scanner and PrintWriter (socket is passed to the thread when it is created).
Code:
public void listen() throws IOException {
while (instream.hasNextLine()==true) {
command = instream.nextLine(); //String command
if (request.startsWith("task name")) {
//performtask
}
}
}