/** A template to control the state of a thread through setting
* an internal flag.
public class StoppableThread extends Thread {
public static final int STOP = 0;
public static final int RUN = 1;
public static final int WAIT = 2;
private int state = RUN;
/** Public method to permit setting a flag to stop or
* suspend the thread. The state is monitored through the
* corresponding checkState method.
*/
public synchronized void setState(int state) {
this.state = state;
if (state==RUN) {
notify();
}
}
/** Returns the desired state of the thread (RUN, STOP, WAIT).
* Normally, you may want to change the state or perform some
* other task if an InterruptedException occurs.
*/
private synchronized int checkState() {
while (state==WAIT) {
try {
wait();
} catch (InterruptedException e) { }
}
return state;
}
/** An example of thread that will continue to run until
* the creating object tells the thread to STOP.
*/
public void run() {
while (checkState()!=STOP) {
...
}
}
}
Note: Brought from our old site: http://www.salearningschool.com/example_codes/ on Jan 2nd, 2017 From: http://sitestree.com/?p=10297
Categories:Programming Code Examples, Java/J2EE/J2ME, Java Threads
Tags:Java/J2EE/J2MEJava Threads
Post Data:2017-01-02 16:04:31
Shop Online: https://www.ShopForSoul.com/
(Big Data, Cloud, Security, Machine Learning): Courses: http://Training.SitesTree.com
In Bengali: http://Bangla.SaLearningSchool.com
http://SitesTree.com
8112223 Canada Inc./JustEtc: http://JustEtc.net (Software/Web/Mobile/Big-Data/Machine Learning)
Shop Online: https://www.ShopForSoul.com/
Medium: https://medium.com/@SayedAhmedCanada
