日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

线程中断问题详解

發(fā)布時(shí)間:2025/4/16 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 线程中断问题详解 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
//線程的中斷操作(1) class MyThread implements Runnable {public void run(){System.out.println("1、進(jìn)入run方法");try{Thread.sleep(10000); //sleep方法會拋出一個(gè)中斷異常}catch(InterruptedException e){System.out.println("2、線程被中斷"); //當(dāng)sleep被打斷時(shí),則執(zhí)行此中斷處理}System.out.println("3、run方法執(zhí)行完成");} } public class ThreadInterruptDemo01 {public static void main(String args[]){MyThread my = new MyThread();Thread t = new Thread(my);t.start();try{Thread.sleep(2000); //主線程休息2秒}catch(Exception e){}t.interrupt(); //中斷線程}}
//線程的中斷操作(2)線程沒有被中斷,interrupt只能中斷sleep,wait等方法 class MyThread implements Runnable {public void run(){System.out.println("1、進(jìn)入run方法");for(int i = 0;i<=10000;i++){System.out.println("線程在執(zhí)行"+"--"+i);}System.out.println("線程正常執(zhí)行完畢");} } public class ThreadInterruptDemo02 {public static void main(String args[]){MyThread my = new MyThread();Thread t = new Thread(my);t.start();t.interrupt(); //中斷線程} }
通過兩段代碼的運(yùn)行結(jié)果可以知道,代碼1的中斷實(shí)現(xiàn)了,而代碼2的中斷沒有實(shí)現(xiàn),interrupt并沒有中斷線程的執(zhí)行,而是中斷了sleep的執(zhí)行。原因何在,這與Interrupt的中斷內(nèi)容有關(guān)。interrupt只能中斷sleep,wait等方法,而通過查詢api可以看到,sleep和wait都有InterruptedException(中斷異常)需要處理。所以可以這樣看:interrupt只能中斷會拋出中斷異常的方法,這才是interrupt的實(shí)際作用。

還有一點(diǎn)需要注意,當(dāng)sleep方法被中斷后,sleep方法后的內(nèi)容依然會被執(zhí)行,相當(dāng)于線程被喚醒進(jìn)入了正常執(zhí)行。

《新程序員》:云原生和全面數(shù)字化實(shí)踐50位技術(shù)專家共同創(chuàng)作,文字、視頻、音頻交互閱讀

總結(jié)

以上是生活随笔為你收集整理的线程中断问题详解的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。