2014-04-06 168 views
0

我希望有人能幫助我解決這個問題。我一直在尋找大約一週的時間來回答這個問題,但沒有結果。在Java中按鍵時暫停/取消暫停線程

我目前有一個自定義線程類實現Runnable,我想暫停按鍵。根據我的研究,我瞭解到最好的方法是使用wait()notify(),由使用密鑰綁定的密鑰觸發。

我的問題是,我怎麼能得到這個工作?我似乎無法設置密鑰綁定而沒有出現問題,並且我如何實現wait()notify()而不會陷入僵局,這一點超出了我的想象。

+0

所以,你們已經經歷了例如[此線程(http://stackoverflow.com/questions/119 89589 /如何到暫停與重新開始,一個線程中的Java-從-另一個線程)?看起來像是同樣的事情。 – eis

+0

不可能在沒有看到你的嘗試的情況下猜測你可能做錯了什麼。否則,你的問題不僅僅是要求某人重新編寫已存在的教程。請通過展示您的代碼嘗試並通過詢問有關您可能被卡住的具體問題來改進您的問題。 –

回答

0

下面是可能讓你開始一個簡單的快照:

class PausableThread extends Thread { 
     private volatile boolean isPaused; 

     @Override 
     public void run() { 
      while (true /* or some other termination condition */) { 
       try { 
        waitUntilResumed(); 
        doSomePeriodicAction(); 
       } catch (InterruptedException e) { 
        // we've been interrupted. Stop 
        System.out.println("interrupted. Stop the work"); 
        break; 
       } 
      } 
     } 

     public void pauseAction() { 
      System.out.println("paused"); 
      isPaused = true; 
     } 

     public synchronized void resumeAction() { 
      System.out.println("resumed"); 
      isPaused = false; 
      notifyAll(); 
     } 

     // blocks current thread until it is resumed 
     private synchronized void waitUntilResumed() throws InterruptedException { 
      while (isPaused) { 
       wait(); 
      } 
     } 

     private void doSomePeriodicAction() throws InterruptedException { 
      System.out.println("doing something"); 
      thread.sleep(1000); 
     } 

    } 

所以,你開始你的線程某處new PausableThread().start();

然後在您的按鈕/在UI線程按鍵聽衆打電話
在OnPauseKeyPress監聽器mPausableThread.pauseAction();,
和OnResumeKeyPress您致電mPausableThread.resumeAction();

T o完全停止踏板,只是中斷它:mPausableThread.interrupt();

希望有所幫助。

1

等待和通知意味着用於同步。在我看來,你想要使用像Thread.suspend(),Thread.stop()和Thread.resume()這樣的方法,但是由於它們引起的鎖定問題的風險已經被棄用了。

的解決方案是使用一個輔助變量,該線程將定期檢查,看它是否應該運行,否則,收益率(或休眠)

爲什麼不使用暫停,停止或恢復:http://docs.oracle.com/javase/6/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

簡單的解決方案: How to Pause and Resume a Thread in Java from another Thread

http://www.tutorialspoint.com/java/java_thread_control.htm