[英]interrupt the thread in java
如您所見,該程序實現了Thread。 我的問題是如何中斷線程並顯示catch阻止消息?
正如我所知,主線程應該在子線程之后完成,但是我認為這是在子線程第二個問題之前我的主線程完成了,您如何解釋呢?
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");
}
}
1)您可以通過在try / catch塊之后立即在主方法中調用newThrd.interrupt()
來中斷線程
2)主線程在子線程之前完成,因為每200ms進行20次Thread.sleep()
表示其生存時間> = 20 * 200 ms
並且子線程的生存時間> = 14 * 600 ms
將中斷發送到cycleone類的一種方法是,在您在cycletwo中創建的newThrd實例上調用Thread.interrupt方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.