Reputation: 19552
I can't figure out what is the problem in the following code:
I have a thread that can be suspended and resumed
Code bellow:
public class CustomThread implements Runnable {
private volatile boolean stop;
private volatile boolean suspend;
String[] names = new String[]{
"A", "B","C","D","E", "F", "G","H","I","J","K", "L"
};
public CustomThread(){
Collections.shuffle(Arrays.asList(names));
System.out.println("Available names:");
System.out.println(Arrays.asList(names));
}
@Override
public void run() {
while(!stop){
synchronized (this) {
if(suspend){
try {
System.out.println("Got suspended");
wait();
System.out.println("Resumed");
} catch (InterruptedException e) {
System.out.println("Got interupted");
}
}
else System.out.println("Suspend false");
}
int randomIdx = new Random().nextInt(names.length);
System.out.println(names[randomIdx]);
}
}
public synchronized void suspend(){
System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>Suspend true");
suspend = true;
}
public synchronized void resume(){
suspend = false;
notify();
}
}
I run the following simple code:
public class CustomTest {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
CustomThread c = new CustomThread();
Thread t = new Thread(c);
t.start();
Thread.sleep(5000);
System.out.println("++++++++++++++++++++++++++++++++");
c.suspend();
}
}
What I am expecting to see is:
Thread custom runs, main sleeps, main suspends the custom thread by c.suspend()
and since main
terminates and noone resumes the thread, the thread remains in wait
state.
But what I see instead is that the CustomThread
prints continually Suspend false
and an element from names
.
What is the problem here? It is like the Thread.sleep(5000)
and c.suspend()
in main don't do anything.
Upvotes: 1
Views: 603
Reputation: 200148
The code is fine as written, but your problem is probably that you are running this through Eclipse and you are overwhelming the console. Put a shorter delay in main
and you'll see good results.
Note: your suspend
method doesn't need to be synchronized
as it only writes to a volatile
variable.
Upvotes: 1
Reputation: 11256
Instead of if(suspend)
you should have while(suspend)
, see the explanation in javadoc here: http://docs.oracle.com/javase/6/docs/api/java/lang/Object.html#wait%28%29
From the javadoc of Object.wait()
:
...interrupts and spurious wakeups are possible, and this method should always be used in a loop
Upvotes: 0