將run()里面的停頓時(shí)間改為是sleep()后,當(dāng)主線程執(zhí)行thread.interrupt()的疑問(wèn)
將run()里面停頓時(shí)間改為是sleep()后,當(dāng)主線程執(zhí)行thread.interrupt()后,this.isInterrupted()的值為ture,那么while語(yǔ)句應(yīng)該停止,為什么還會(huì)執(zhí)行Thread.sleep()從而拋出異常?視頻8分鐘開(kāi)始那里
將run()里面停頓時(shí)間改為是sleep()后,當(dāng)主線程執(zhí)行thread.interrupt()后,this.isInterrupted()的值為ture,那么while語(yǔ)句應(yīng)該停止,為什么還會(huì)執(zhí)行Thread.sleep()從而拋出異常?視頻8分鐘開(kāi)始那里
2018-08-22
舉報(bào)
2019-07-10
薇辣醬?說(shuō)得對(duì), 是概率問(wèn)題,子線程中while (!this.isInterrupted()) 這句話運(yùn)行的時(shí)間非常短,子線程的絕大部分時(shí)間都在Thread.sleep(xxxx);這句話上,所以在主線程中將子線程中斷的時(shí)候(主線程執(zhí)行thread.interrupt()的時(shí)候),子線程有極大的概率處于sleep中,然后就會(huì)報(bào)sleep中斷錯(cuò)誤(sleep interrupted)。
簡(jiǎn)單的驗(yàn)證:
在子線程的sleep語(yǔ)句前后各加一個(gè)輸出,比如“子線程將睡眠XX秒”和“子線程睡眠結(jié)束”,然后你會(huì)發(fā)現(xiàn)異常都出現(xiàn)在“子線程將睡眠XX秒”這句后面,然后沒(méi)有出現(xiàn)相匹配的“子線程睡眠結(jié)束”,也就是說(shuō)主線程在將子線程中斷的時(shí)候,子線程都處于sleep的狀態(tài)(絕大部分時(shí)候)。
處于非sleep的狀態(tài)如果真的試出來(lái)了,應(yīng)該是會(huì)出現(xiàn)“子線程將睡眠XX秒”和“子線程睡眠結(jié)束”,然后子線程退出循環(huán)。
2019-04-18
我想明白了,因?yàn)閠hread是從上一次停下來(lái)的位置開(kāi)始運(yùn)行的,不是從while (!this.isInterrupted())這里開(kāi)始。而sleep占用了while循環(huán)大多數(shù)時(shí)間,所以上次大概率是在sleep()這里停的。
所以重新運(yùn)行的時(shí)候,一開(kāi)始就拋出了InterruptedException異常,同時(shí)this.isInterrupted()被置為false。然后while循環(huán)就一直運(yùn)行下去了。
我將run循環(huán)內(nèi)容做了一些修改,你可以看的更清楚。
public void run() {
????int i = 0;
????while (!this.isInterrupted()) {
????????System.out.println(i);
????????try {
????????????Thread.sleep(4000);
?????????} catch (InterruptedException e) {
????????????e.printStackTrace();
????????????System.out.println(i+1000);
????????}
????????System.out.println(i);
????????i++;
????}
}
輸出為:
Starting Thread...
0
Interrupting Thread...
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at WrongWayStopThread.run(WrongWayStopThread.java:28)
1000
0
1
1
2
2
3
Stopping Application...
2019-04-18
我也沒(méi)弄明白這個(gè)問(wèn)題,求解答。。。
2019-04-08
this.isInterrupted()是測(cè)試線程的狀態(tài)是否是interrupted的。
這個(gè)狀態(tài)時(shí)由thread.interrupt()方法來(lái)置位的,但是thread.interrupt()方法置位為interrupted狀態(tài)的前提是線程處于非阻塞狀態(tài),否則thread.interrupt()只會(huì)把interrupted清除并且拋出異常。
因?yàn)檫@里調(diào)用Thread.sleep()使線程處于阻塞狀態(tài),所以線程非但沒(méi)有被置為interrupted,反而拋出了異常。
while循環(huán)的執(zhí)行大部分時(shí)間應(yīng)該是在Thread.sleep()上的,幾乎不可能在Thread.sleep()剛好結(jié)束而還沒(méi)有進(jìn)行while(true)判斷的時(shí)候thread.interrupt()置位為interrupted狀態(tài)
2018-11-13
thread.interrupt()方法的作用是喚醒阻塞的線程,并拋出異常。當(dāng)sleep后,線程阻塞,thread.interrupt()方法執(zhí)行后,線程又被喚醒并拋出異常。因?yàn)榫€程被喚醒,所以this.isInterrupted()的值為false,while語(yǔ)句繼續(xù)
2018-08-22
先拋出的一場(chǎng),然后重置變量