2017-11-26 7 views
-2
public class InterruptTest extends Thread 
{ 
    public void run() 
    { 
    try { 
     Thread.sleep(1000); 
     System.out.println("Finished!"); 
     } 
    catch (InterruptedException e) { 
     System.out.println("I am interrupted!"); 
     System.out.println(Thread.interrupted());// showing the result after exception throw as well as flag set to false 
     System.exit(-1); 
     } 
    } 
    public static void main(String args[]) 
    { 
     InterruptTest t1 = new InterruptTest(); 
     Thread t= new Thread(t1); 

     t.start(); 
     System.out.println(t.isInterrupted());// ask for the judgment in first time before calling interrupt(). 

     t.interrupt(); 
     System.out.println(t.isInterrupted());// ask for the judgment in second time after calling interrupt(). 
     System.out.println(t.isInterrupted());// ask for the judgment in third time after calling interrupt(). Very Puzzled!!! 
     System.out.println(t.isInterrupted());// ask for the judgment in fourth time after calling interrupt(). 
    } 
} 

Console Display: 

false// sure 
true// not sure 
true// not sure 
true// not sure 
I am interrupted!// sure 
false// sure 

false// sure 
true// not sure 
true// not sure 
false// not sure 
I am interrupted!// sure 
false// sure 

false// sure 
true// not sure 
false// not sure 
false// not sure 
I am interrupted!// sure 
false// sure 

コードは、Javaスレッドとinterrupt()メソッドに関係しています。同じコードを何度も実行することで予期しない結果がどうなるか教えてください。なぜこれらの結果は一意ではありませんか? .................................................. ..................................皆さん、ありがとうございました!Javaスレッドと割り込み、強力なパズル

+0

あなたが私のパズルについて明確でない場合は、気軽に! ☺ –

答えて

0

あなたのコードは同時実行性の動作をしています。つまり、どのスレッドが同時に起動しているのか、どのスレッドが停止するのかを判断することはできません。

+0

あなたの 'main'メソをラップするスレッドがあるので、複数のスレッドがあることに注意してください。 –

+0

あなたの意味を理解していないのは申し訳ありません、私はt.isInterrupted()をinterrupt()それは私に3つの同じ結果を与えるはずです。 –

+0

私はメインスレッドも考慮しなければならないと言いました。あなたのスレッドが中断されているかどうかを知ることはできません。スレッド内の命令はこれ以上シーケンシャルではないことに気をつけてください。 –

関連する問題