What's the best way to start, pause, resume, and stop a thread in Java? I wrote a little code to test, and it works how I wanted, but I'm not sure if this is the best way. If there are many threads going like this, wouldn't it wasting tons of resources while they're checking run and pause all the time?
public class ThreadTest {
public static void main(String[] args) {
try {
Counter t = new Counter();
t.start();
Thread.sleep(4000);
t.pause();
Thread.sleep(5000);
t.pause();
Thread.sleep(4000);
t.finish();
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Counter extends Thread {
int c;
boolean run, pause;
public Counter() {
c = 0;
}
public void run() {
run = true;
while (run == true) {
if (!pause) {
c++;
System.out.println(c);
try {
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
System.out.println("Stop!");
}
public void finish() {
run = false;
}
public void pause() {
pause = !pause;
}
}