Hello all,
I am having some troubles to understand how I have to stop a running thread. I'll try to explain it by example. Assume the following class:
public class MyThread extends Thread {
protected volatile boolean running = true;
public void run() {
while (running) {
synchronized (someObject) {
while (someObject.someCondition() == false && running) {
try {
someObject.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// do something useful with someObject
}
}
}
public void halt() {
running = false;
interrupt();
}
}
Assume the thread is running and the following statement is evaluated to true:
while (someObject.someCondition() == false && running)
Then, another thread calls MyThread.halt(). Eventhough this function sets 'running' to false (which is a volatile boolean) and interrupts the thread, the following statement is still executed:
someObject.wait();
We have a deadlock. The thread will never be halted.
Then I came up with this, but I am not sure if it is correct:
public class MyThread extends Thread {
protected volatile boolean running = true;
public void run() {
while (running) {
synchronized (someObject) {
while (someObject.someCondition() == false && running) {
try {
someObject.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// do something useful with someObject
}
}
}
public void halt() {
running = false;
synchronized(someObject) {
interrupt();
}
}
}
Is this correct? Is this the most common way to do this?
This seems like an obvious question, but I fail to come up with a solution. Thanks a lot for your help.