首页 > 解决方案 > java中的暂停和恢复线程不起作用

问题描述

我想分别使用 wait()/notify() 应用挂起/恢复线程。我已经反复尝试解决这个问题,但我不能,所以请帮助我并解释为什么 notify(); 不会使计数器线程可运行:

public class Suspend {
boolean isSuspend = false;
int counter = 0;

synchronized public void suspend() {    
    isSuspend = true;
    System.out.println("The counter was suspended!");
}

synchronized public void resume() {
    isSuspend = false;
    System.out.println("The counter was resumed :)");
    notify();
}

public static void main(String[] args) {
    Thread.currentThread().setName("Main Thread");
    Suspend suspend = new Suspend();

    Thread counterThread = new Thread(new Runnable() {
        synchronized public void run() {
            while(!suspend.isSuspend) {
                System.out.println(suspend.counter++);
                try { Thread.sleep(1000); }
                catch (InterruptedException e) {}
            }
            try {
                while(suspend.isSuspend)
                    wait();
                }
            catch (InterruptedException e) {}
        }
    }, "Counter Thread");

    Thread suspendResumeThread = new Thread(new Runnable() {
        synchronized public void run() {
            while(true) {
                try {
                    Thread.sleep(5000);
                    suspend.suspend();
                    Thread.sleep(5000);
                    suspend.resume();
                } catch (InterruptedException e) {}
            }
        }
    }, "Suspend/Resume Thread");

    counterThread.start();
    suspendResumeThread.start();
}

}

输出如下: 0 1 2 3 4 The counter was suspended! The counter was resumed :) The counter was suspended! The counter was resumed :) ... and so on.

标签: javaeclipsemultithreading

解决方案


问题是这些行:

while (suspend.isSuspend)
    wait();
}

在你的counterThreadRunnable 中。

你在等待Runnable,而不是在suspend对象上

您需要同步suspend并调用 wait() on suspend

synchronized (suspend) {
    while (suspend.isSuspend)
        suspend.wait();
    }
}

此外,您的run方法不需要同步。


推荐阅读