-1

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;
   }

}
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Sean Stack
  • 31
  • 4

1 Answers1

1

What's the best way to start, pause, resume, and stop a thread in Java? 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?

The best way is to not explicitly start and pause threads. You're right, it is a waste of time.

Thread pausing should be done automatically by the operating system when your thread blocks itself on a stream, end of a producer/consumer queue, or other data structure that facilitates concurrency.

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245