from sdojqy1122
突然碰到一个问题,线程的暂停与继续,我想了想,去使用JDK给我们提供的suspend方法、interrupt方法??suspend()方法让这个线程与主线程都暂停了,谁来唤醒他们??明显这个不好用,要用的话,恐怕得另写唤醒线程了!interrupt方法,这个方法实际上只能中断当前线程!汗!
既然JDK解决不了偶的问题,偶只能自己写了!
这个时候想到了Object的wait()和notifyAll()方法。使用这两个方法让线程暂停,并且还能恢复,我只需要封装一下,就能够变成非常之好用的代码了!如下请看:
我新建Thread类继承MyThread只需实现runPersonelLogic()即可跑你自己的逻辑啦!!!
另外调用setSuspend(true)是当前线程暂停/ 等待,调用setSuspend(false)让当前线程恢复/唤醒!自我感觉很好使!
- 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);
- }
- }