2016-04-27 10 views
1

私は、女性の飼育動物が妊娠可能(Runnableを実装するクラス)することができる小さなプロジェクトを実現しています。自動的にスレッドを停止するメソッドを呼び出す方法は?

ここに私の妊娠のクラスです:

private final class Gestation implements Runnable //inner class of Viviparous 
{             
     private boolean isWorking; 
     private Viviparous[] babies; 
     private final int time_end; 
     private int time_left; 
     private Enclosure e; 

     public Gestation(Viviparous[] b, Enclosure e) 
     { 
      if(Viviparous.this instanceof Lion) 
       this.time_end = Lion.TIME_GESTATION; 
      else if(Viviparous.this instanceof Gazelle) 
       this.time_end = Gazelle.TIME_GESTATION; 
      else if(Viviparous.this instanceof Otter) 
       this.time_end = Otter.TIME_GESTATION; 
      else 
       this.time_end = 0; 
      this.time_left = this.time_end; 
      this.e = e; 
      this.b =b; 

      this.isWorking = true; 
      new Thread(this).start(); 
     } 

     public Viviparous[] getBabies() 
     { 
      return this.babies; 
     } 

     public boolean isWorking() 
     { 
      return this.isWorking; 
     } 

     public void stop() 
     { 
      if(this.time_left == 0) 
      { 
       Thread.currentThread().stop(); 
       this.isWorking = false; 
       System.out.println("Gestation ended"); 

       Viviparous.this.calve(this.e); //calving in Enclosure e. 
      } 
     } 

     public void run() 
     { 
      while(this.isWorking) 
      { 
       this.time_left--; 
       try 
       { 
        Thread.sleep(400L); 
       } 
       catch (InterruptedException e) 
       { 
        e.printStackTrace(); 
       } 
       if((this.time_left)%10==0 && this.time_left != 0) 
        System.out.println("Gestation will end in "+this.time_left+" days."); 
      } 
     } 

} 

私は(停止をトリガしたい)TIME_LEFT == 0 は私がstop()メソッドを持っていなかった右の前に、のみ(実行した場合)でtime_left == time_endのときにループが停止し、次にViviparousのcalve()が呼び出されました。この最後のメソッドは、ユーザーに入力した赤ちゃんに名前を付けるように求めます。 問題は、私のプログラマーが既にユーザーに現在のメニューからオプションを選択するように求めていることです。 赤ちゃんの名前とメニューオプションを入力する間に競合があると思います。

+0

'Thread.stop()'は[安全でなく、非推奨]です(https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#stop())。それを呼び出さないでください。 –

+0

私はそれを削除します!彼らは彼らの最後に達すると、スレッドはとにかく停止しますか? – Aleks

+0

'isWorking'はこのスレッドでは決してfalseに設定されないので(volatileではないので、確実に別のスレッドからはできません)、スレッドは終了しません。 –

答えて

0

揮発性のブール値フィールド(isWorkingなど)を作成し、それを設定するメソッドを提供します。そのメソッドを呼び出すことによってスレッドを停止することができます。とにかく)deprectedはThread.stop(なし必要

private volatile boolean isWorking = true; 

public stopThread() { 
    this.isWorking = false; 
} 

...そうでなければ気付かれないことがあり、変数は揮発性であることを確認してください。

+0

ありがとう!スレッドを自動的に停止したい。私はObserver/Observerパターンを探しています。 – Aleks

1

スレッドを自動的に停止します。

実行メソッドが例外を返すか、例外をスローすると、スレッドは停止します。スレッドを停止させたい場合は、run()から戻してください。 のときに自動的に停止したい場合は、スレッドの最上位ループでtime_leftをテストし、time_left == 0のときに戻してください。