zoukankan      html  css  js  c++  java
  • Java 线程暂停与继续

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

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

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

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

        

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

    [java] view plaincopy 

    public abstract class MyThread extends Thread {  

      

        private boolean suspend = false;  

      

        private String control = ""; // 只是需要一个对象而已,这个对象没有实际意义  

      

        public void setSuspend(boolean suspend) {  

            if (!suspend) {  

                synchronized (control) {  

                    control.notifyAll();  

                }  

            }  

            this.suspend = suspend;  

        }  

      

        public boolean isSuspend() {  

            return this.suspend;  

        }  

      

        public void run() {  

            while (true) {  

                synchronized (control) {  

                    if (suspend) {  

                        try {  

                            control.wait();  

                        } catch (InterruptedException e) {  

                            e.printStackTrace();  

                        }  

                    }  

                }  

                this.runPersonelLogic();  

            }  

        }  

      

        protected abstract void runPersonelLogic();  

          

        public static void main(String[] args) throws Exception {  

            MyThread myThread = new MyThread() {  

                protected void runPersonelLogic() {  

                    System.out.println("myThead is running");  

                }  

            };  

            myThread.start();  

            Thread.sleep(3000);  

            myThread.setSuspend(true);  

            System.out.println("myThread has stopped");  

            Thread.sleep(3000);  

            myThread.setSuspend(false);  

        }  

    }  


  • 相关阅读:
    属性与字段的区别
    修改LVDS支持1024*600分辨率
    Altium designer 10如何设置标题栏
    嵌入式C开发人员的最好的0x10道笔试题
    进程线程及堆栈关系的总结
    GDB调试
    c语言
    如何使用autotools生成Makefile
    ubuntu NFS
    Ubuntu安装配置TFTP服务
  • 原文地址:https://www.cnblogs.com/luckForever/p/7254212.html
Copyright © 2011-2022 走看看