突然碰到一個問題,線程的暫停與繼續,我想了想,去使用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);
}
}