Java - general

pause a thread

java.lang.Threads
There is the possibility to pause a thread with Thread.suspend() and Thread.resume(). But these methods are old for a good reason. An intensive using can lead to a deadlock.



The better method is to pause the thread as follows:

MyThread thread = new MyThread();
thread.start();
 
while (true) {
   // Here can be a Code which will be worn out while the thread is running...
 
   // Now the thread will be paused:
   synchronized (thread) {
      thread.pause();
   }
 
   // Here can be a Code which will be worn out while the thread is running...
 
   // Resume the thread
   synchronized (thread) {
      thread.proceed();
   }
 
   // Here can be a Code which will be worn out while the thread is running...
}
 
class MyThread extends Thread {
   boolean fPause = false;
 
   public void run() {
      while (true) {
         // any Code...
 
         // check, if pausing is announced:
         synchronized (this) {
            while (fPause) {
               try {
                  wait();
               } catch (Exception e) {
                  e.printStackTrace();
               }
            }
         }
 
         // any Code...
       }
   }
 
   public void pause() {
      fPause = true;
   }
 
   public void proceed() {
      fPause = false;
      notify();
   }
}

Eigene Werkzeuge
Werkzeuge

gratis Counter by GOWEB
seit 9.10.2007