Reputation: 35
I have 2 Threads, one that's polling a mailbox for messages then sleeping while (!quit)
and another that's supposed to change the quit
flag should the user enter 'Q'
. It seems that the scanning Thread blocks the other Thread from executing until there's some input (usually 2 lines). I've tried changing the priority of the Threads and the order in which they start, to no avail.
class quitThread extends Thread {
public void run() {
char c;
Scanner scanner = new Scanner(System.in);
do {
c = scanner.nextLine().toUpperCase().charAt(0);
} while (c != 'Q');
quit = true;
}
}
class recieveThread extends Thread {
public void run() {
System.out.println("thread started");
while (!quit) {
try {
MailHandler handler = new MailHandler();
handler.recieve();
System.out.println("Sleeping");
sleep(_sleepinterval);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I know I have to worry about mutex and synchronisation, but I want the Threads to at least work before I start worrying about it. EDIT: This is how I'm starting the threads:
void go() throws Exception{
char c;
System.out.println("S or R");
Scanner s = new Scanner(System.in);
c = s.nextLine().toUpperCase().charAt(0);
MailHandler handler = new MailHandler();
QuitThread q = new QuitThread();
q.setPriority(java.lang.Thread.MIN_PRIORITY);
RecieveThread rc = new RecieveThread();
rc.setPriority(java.lang.Thread.MAX_PRIORITY);
switch (c){
case 'S':
handler.send("[email protected]", "hello there");
break;
case 'R':
rc.start();
q.start();
break;
default :
break;
}
}
Note: the priorities weren't originally there, it's something i just tried and it didn't make any difference.
Upvotes: 1
Views: 310
Reputation: 5159
How are two different instances of two different classes sharing the quit
variable?
Try using an AtomicBoolean, shared between your two threads.
Also, how do you know the scanning thread is blocking the other one? From your code, I can't see them sharing any resources except for the quit
variable.
Maybe you see the "thread started" message and then you don't see the "sleeping" message for a while because the receiveThread is stuck in the handler.receive() method...
Upvotes: 3
Reputation: 84013
As you can see they won’t work without synchronization, so fix that first.
Upvotes: 0