i started to read about how to stop, interrupt, suspend and resume safely a java thread, i found on oracle documentation the following solutions :
1- How to stop a thread safely :
private volatile Thread blinker;
public void stop() {
blinker = null;
}
public void run() {
Thread thisThread = Thread.currentThread();
while (blinker == thisThread) {
try {
Thread.sleep(interval);
} catch (InterruptedException e){
}
repaint();
}
}
- To stop a thread i can use a boolean variable instead of volatile Thread, but why Oracle insists on affecting null to the started thread? is there any secret (e.g liberating resources allocated using finalizer) behind doing it like this?
2- How to interrupt a thread which waits for long time :
public void stop() {
Thread moribund = waiter;
waiter = null;
moribund.interrupt();
}
- why should i create new variable moribund and not using directly waiter.interrupt()?
3- How to suspend and resume a thread :
private volatile boolean threadSuspended;
public void run() {
while (true) {
try {
Thread.sleep(interval);
if (threadSuspended) {
synchronized(this) {
while (threadSuspended)
wait();
}
}
} catch (InterruptedException e){
}
repaint();
}
}
public synchronized void mousePressed(MouseEvent e) {
e.consume();
threadSuspended = !threadSuspended;
if (!threadSuspended)
notify();
}
- Why inside run method they added the loop while (threadSuspended) because i don't understand what the purpose of adding it, and my code can be compiled and run correctly without it (with same output results).
Source link http://docs.oracle.com/javase/8/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html