Pausing a Thread


MyThread thread = new MyThread(); thread.start(); while (true) {    // do work... synchronized (thread) {       thread.doWait = true;    }    // do work...    synchronized (thread) {       thread.doWait = false;       thread.notify();    } } class MyThread extends Thread {    boolean doWait = false;    public void run() {       while (true) {          // do work...          synchronized (this) {             while (doWait) {                   wait();                }                catch (Exception e) {                }             }          }       }    } }



This phrase shows you how to pause a thread from a different thread. In the phrase, we use the variable doWait as a flag to pause the execution of MyTHRead. In the run() method of MyTHRead, we check the doWait flag after performing some work in a loop to determine if we need to pause the thread's execution. If the doWait flag is set to true, we call the Object.wait() method to pause the thread's execution.

When we want to wake the thread up, we set the doWait flag to false and call the tHRead.Notify() method to wakeup the thread and continue its execution loop.

Having a thread pause itself is a simpler task. The code below shows how you would pause the current thread:

long numMilliSecondsToSleep = 5000; Thread.sleep(numMilliSecondsToSleep);


This code would pause the current thread for 5000 milliseconds which is the equivalent of five seconds.

In addition to the methods described above, the Thread.suspend() and Thread.resume() methods provide a mechanism for pausing threads, however these methods have been deprecated. Use of these methods can often result in a deadlock. I only mention these methods so that you know to avoid using them. Because use of these methods is not recommended, they are not discussed any further here.




JavaT Phrasebook. Essential Code and Commands
Java Phrasebook
ISBN: 0672329077
EAN: 2147483647
Year: 2004
Pages: 166

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net