Java 线程暂停与继续

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

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

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

 

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

    

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

 

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值