Stop方法不推薦使用,我給個具體的例子:
- public class DeprecatedStop extends Object implements Runnable {
- public void run() {
- int count = 0;
- while ( count <20 ) {
- System.out.println("Running ... count=" + count);
- count++;
- try {
- Thread.sleep(300);
- } catch ( InterruptedException x ) {
- // ignores
- }
- }
-
- // the code maybe not executed
- System.out.println("stoped");
- }
- public static void main(String[] args) {
- DeprecatedStop ds = new DeprecatedStop();
- Thread t = new Thread(ds);
- t.start();
- try {
- Thread.sleep(2000);
- } catch ( InterruptedException x ) {
- // ignore
- }
- // Abruptly stop the other thread in its tracks!
- t.stop();
- }
- }
可能的運行結果:
- Running ... count=0
- Running ... count=1
- Running ... count=2
- Running ... count=3
- Running ... count=4
- Running ... count=5
- Running ... count=6
可以發現程式中的列印stoped並沒有執行,所以說如果在程式中有其他動作,如果線程突然stop是會帶來嚴重的影響的。所以怎麼也應該使用該操作。當然如果是我上面的程式碼突然stop的影響其實是沒有的,但是如果是其他開啟檔案最後需要釋放或者什麼的就會帶來嚴重的影響了。
如何在程式中對其進行停止呢?
- public class AlternateStop extends Object implements Runnable {
- private volatile boolean stopRequested;
- private Thread runThread;
- public void run() {
- runThread = Thread.currentThread();
- stopRequested = false;
- int count = 0;
- while ( !stopRequested ) {
- System.out.println("Running ... count=" + count);
- count++;
- try {
- Thread.sleep(300);
- } catch ( InterruptedException x ) {
- Thread.currentThread().interrupt(); // re-assert interrupt
- }
- }
-
- System.out.println("stoped");
- }
- public void stopRequest() {
- stopRequested = true;
- if ( runThread != null ) {
- runThread.interrupt();
- }
- }
- public static void main(String[] args) {
- AlternateStop as = new AlternateStop();
- Thread t = new Thread(as);
- t.start();
- try {
- Thread.sleep(2000);
- } catch ( InterruptedException x ) {
- // ignore
- }
- as.stopRequest();
- }
- }
可能的運行結果如下:
- Running ... count=0
- Running ... count=1
- Running ... count=2
- Running ... count=3
- Running ... count=4
- Running ... count=5
- Running ... count=6
- stoped
這樣我們就解決了強制 stop的問題。