2017-11-06 28 views
-1

スレッドはArrayListに格納されているため、後で名前で動的に設定することができます。インターネット上には多くの例がありますが、これについてはすべて理解できますが、私はうまくいかないので、選択したスレッドは停止しません。 私のせいで何ができますか?arrayList内のスレッドは割り込みを知らない

public class Szal { 
    static ArrayList<MyThread> myThread; 
    static String[] names; 

    public Szal() { 
     myThread = new ArrayList<MyThread>(); 
     names = new String[]{"EZ", "AZ"}; 

     for (int i = 0; i < names.length; i++) { 
      MyThread t = new MyThread(names[i]); 
      myThread.add(t); 
      t.start(); 
     } 
    } 

    public static void main(String[] args) { 
     new Szal(); 

     Thread[] thread = new Thread [Thread.activeCount()]; 
     int m = Thread.enumerate (thread); 
     for (int i = 0; i < m; i++) { 
      System.out.println (thread[i].getName()); 
     } 

     // Why is this not working? 
     for (Thread t : myThread) { 
      if (t.getName().equalsIgnoreCase("EZ")) { 
       t = Thread.currentThread(); 
       t.interrupt(); 
       myThread.remove(t); 
      } 
     } 

     Thread[] threads = new Thread [Thread.activeCount()]; 
     int c = Thread.enumerate (threads); 
     for (int i = 0; i < c; i++) { 
      System.out.println (threads[i].getName()); 
     } 
    } 

    class MyThread extends Thread { 
     public MyThread(String name) { 
      super(name); 
     } 

     public void run() { 
      while (true) { 

      } 
     } 
    } 
} 
+0

ここではどのスレッドが中断されていますか? –

+0

なぜ 't = Thread.currentThread();'をやっているのですか?あなたがそれを修正して 't'を中断した後でさえ、あなたはそれが他の何かを実際に行うためにフラグを設定するためにスレッドがインターハンド状態になる必要があります。 http://idownvotedbecau.se/nodebugging/ – Oleg

答えて

0
//this why not working??? 
for(Thread t : myThread){ 
    if(t.getName().equalsIgnoreCase("EZ")){ 
     t= Thread.currentThread(); 
     t.interrupt(); 
     myThread.remove(t); 
    } 
} 

あなたは、リスト内のすべてのスレッドを反復処理し、あなたが名前EZと一つに到達するとすぐに自分自身をiterrupt。私はそれがあなたが実際にやろうとしていることかどうかは分かりません。あなたの質問はEZ-Threadを中断したいと思ったように聞こえました。その場合は、t = Thread.currentThread()という行は省略してください。

「作業していない」という意味を正確に説明していないので、中断したスレッドが引き続き実行されていることを意味していると思います。これは、スレッドが中断した場合にその事実をチェックしている操作を実際に実行しているスレッドがないためです。

あなたはこのようごMyThread-実装を変更する場合があります:

class MyThread extends Thread{ 

    public MyThread(String name) { 
     super(name); 
    } 

    public void run() { 
     try { 
      while(true){ 
       Thread.sleep(10); 
      } 
     } 
     catch(InterrutedException ie) { 
      // leads to the end of the thread 
     } 
    } 
} 

または代わり

while(!interrupted()){ 

} 

ああ、すべてのスレッドを中断し、出力間のビットを待ちます。スレッドの起動と終了は時間がかかる複雑な作業です。スレッドを確実にシャットダウンする完全に機能するコードでも、直後にすべてのスレッドをリストすると、中断されたスレッドがアクティブとして表示されることがあります。

関連する問題