How to implement Java threads blocking / wake (and pause / resume similar)

 The following is the thread blocks / Wake major code

public  class the MyThread the extends the Thread { 

        // meaningless 
        Private  Final Object Lock = new new Object (); 

        // Flag thread obstruction 
        Private  Boolean PAUSE = to false ; 

        / ** 
         * Set the thread is blocked 
         * / 
        public  void pauseThread () {
             the this . = PAUSE to true ; 
        } 

        / ** 
         * this method calls the thread recovery operation implemented 
         * / 
        public  void ResumeThread () {
             the this .pause = to false ;
            the synchronized (Lock) {
                 // wake-up thread 
                ; () lock.notify 
            } 
        } 

        / ** 
         * This method can only be implemented in the run method, or will block the main thread, resulting in page no response 
         * / 
        void onPause () {
             the synchronized ( Lock) {
                 the try {
                     // thread waiting / blocking 
                    lock.wait (); 
                } the catch (InterruptedException E) { 
                    e.printStackTrace (); 
                } 
            } 
        } 

        @Override 
        public  void RUN () {
            Super .run ();
             // Flag thread turn 
            isWait = to true ;
             // been circulating 
            the while ( to true ) {
                 IF (PAUSE) {
                     // thread blocked / wait 
                    the onPause (); 
                } 
                the try {
               // program executed every 50 milliseconds you can change the value 
                    Thread.sleep (50 );  
                     // here you write your code code code your important things to say three times 
                } the catch (Exception E) { 
                    e.printStackTrace (); 
                    BREAK ;
                }
            }
        }
    }

how to use?

// 1. Create your own thread 
the Thread myThread = new new MyThread (); 

// 2. Start a thread in the right place (you need to start somewhere) 
myThread.start (); 

// blocked thread 3. After the start of / pause 
myThread.pauseThread (); 

// 4. and blocking / pause wake up after thread / continue 
myThread.resumeThread ();

 

Guess you like

Origin www.cnblogs.com/bieyaoxiguan/p/11493590.html