Android Java 线程暂停与继续

来源:互联网 发布:linux文件夹拷贝 编辑:程序博客网 时间:2024/04/29 01:02

 突然碰到一个问题,线程的暂停与继续,我想了想,去使用JDK给我们提供的suspend方法、interrupt方法??suspend()方法让这个线程与主线程都暂停了,谁来唤醒他们??明显这个不好用,要用的话,恐怕得另写唤醒线程了!interrupt方法,这个方法实际上只能中断当前线程!汗!

        既然JDK解决不了偶的问题,偶只能自己写了!

        这个时候想到了Object的wait()和notifyAll()方法。使用这两个方法让线程暂停,并且还能恢复,我只需要封装一下,就能够变成非常之好用的代码了!如下请看:

 

        我新建Thread类继承MyThread只需实现runPersonelLogic()即可跑你自己的逻辑啦!!!

    

        另外调用setSuspend(true)是当前线程暂停/ 等待,调用setSuspend(false)让当前线程恢复/唤醒!自我感觉很好使!

 

[java] view plaincopy
  1. public abstract class MyThread extends Thread {  
  2.   
  3.     private boolean suspend = false;  
  4.   
  5.     private String control = ""// 只是需要一个对象而已,这个对象没有实际意义  
  6.   
  7.     public void setSuspend(boolean suspend) {  
  8.         if (!suspend) {  
  9.             synchronized (control) {  
  10.                 control.notifyAll();  
  11.             }  
  12.         }  
  13.         this.suspend = suspend;  
  14.     }  
  15.   
  16.     public boolean isSuspend() {  
  17.         return this.suspend;  
  18.     }  
  19.   
  20.     public void run() {  
  21.         while (true) {  
  22.             synchronized (control) {  
  23.                 if (suspend) {  
  24.                     try {  
  25.                         control.wait();  
  26.                     } catch (InterruptedException e) {  
  27.                         e.printStackTrace();  
  28.                     }  
  29.                 }  
  30.             }  
  31.             this.runPersonelLogic();  
  32.         }  
  33.     }  
  34.   
  35.     protected abstract void runPersonelLogic();  
  36.       
  37.     public static void main(String[] args) throws Exception {  
  38.         MyThread myThread = new MyThread() {  
  39.             protected void runPersonelLogic() {  
  40.                 System.out.println("myThead is running");  
  41.             }  
  42.         };  
  43.         myThread.start();  
  44.         Thread.sleep(3000);  
  45.         myThread.setSuspend(true);  
  46.         System.out.println("myThread has stopped");  
  47.         Thread.sleep(3000);  
  48.         myThread.setSuspend(false);  
  49.     }  
  50. }  
0 0