2017-02-24 91 views
-1

您可以看到這個程序實現了Thread。我的問題是,我如何中斷線程並顯示catch catch消息?中斷java中的線程

因爲我知道主線程應該完成後的子線程,但我認爲這裏是我的主線程完成之前子線程第二個問題是你怎麼解釋它?

public class cycleone implements Runnable { 
     int cases; 
    Thread thrd; 
    cycleone(int pooya){ 
     cases=pooya; 
    } 
    //child thread 
    public void run(){ 
     try{ 
      for(int i=0;i<=14;i++){ 
       System.out.println("this is "+i+""+cases); 
       Thread.sleep(600); 
       } 
      } 
     catch(InterruptedException ext){ 
      System.out.print("no"); 
     } 
    } 

} 


public class cycletwo { 
    public static void main(String[] args) { 
    cycleone one=new cycleone(4); 
    Thread newThrd=new Thread(one); 
    newThrd.start(); 
    // main thread 
    try{ 
     for(int i=0;i<=20;i++){ 
     System.out.println("/"); 
     Thread.sleep(200); 
     } 
    } 
    catch(InterruptedException exc) { 
     System.out.println("thread is end"); 
    } 
    System.out.println("thread is ending"); 
    } 
} 

回答

0

一個你可以發送一箇中斷到cycleone類的方法是調用您在cycletwo創建newThrd實例的方法了Thread.interrupt。

2

1)你可以通過調用中斷線程:在你的主要方法newThrd.interrupt()的try/catch塊

2)主線程子線程之前完成之後,因爲20次每200毫秒Thread.sleep()意味着它的續航時間爲> = 20 * 200毫秒

和子線程的續航時間爲> = 14 * 600毫秒

+0

所以我說這可能是比子線程更早主線程結束? –