国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Java > 正文

Java線程停止的方法

2019-11-06 06:38:36
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

java線程停止的方式

可以調(diào)用stop()方法,但是該方法已經(jīng)被停用,同時(shí)該方法會(huì)使線程當(dāng)前未完成的任務(wù)丟失可以調(diào)用interrupt()方法標(biāo)記當(dāng)前線程為停止?fàn)顟B(tài),在線程中調(diào)用isInterrupted()方法,如果該方法返回true,進(jìn)行停止線程操作(return,throw),interrupt、interrupted 、isInterrupted 詳解

下面演示線程的兩種停止方法

stop()方法停止


public class ThreadStopTest { public static void main(String[] args) { StopThread stopThread = new StopThread(); Thread t = new Thread(stopThread); t.start(); try { Thread.sleep(50); } catch (InterruptedException ignore) { // ignore this exception } t.stop(); }}class StopThread implements Runnable { @Override public void run() { System.out.運(yùn)行結(jié)果: 運(yùn)行結(jié)果

interrupt()方法停止


public class ThreadInterruptTest { public static void main(String[] args) { InterruptThread interruptThread = new InterruptThread(); Thread t = new Thread(interruptThread); t.start(); try { Thread.sleep(50); } catch (InterruptedException ignore) { // ignore this exception } t.interrupt(); }}class InterruptThread implements Runnable { @Override public void run() { System.out.println("thread is start"); for (int i = 0; i < 10000000; i++) { if (Thread.currentThread().isInterrupted()) { return; } System.out.println(i); } }}

運(yùn)行結(jié)果: 運(yùn)行結(jié)果

用stop()停止線程,在線程中無(wú)法得知,對(duì)未完成任務(wù)無(wú)法處理,使用interrupt()停止,在線程中能夠進(jìn)行判斷,對(duì)于未完成任務(wù)能夠進(jìn)行處理

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 兴国县| 宣化县| 崇左市| 三原县| 建昌县| 汉源县| 新余市| 上饶市| 宾阳县| 荣昌县| 西畴县| 鲜城| 积石山| 紫云| 克拉玛依市| 虞城县| 阳春市| 富锦市| 沙湾县| 慈利县| 河北省| 沾化县| 蓝田县| 金华市| 东兰县| 高阳县| 垣曲县| 哈尔滨市| 普陀区| 乐清市| 东阳市| 汽车| 六盘水市| 呈贡县| 惠州市| 山阴县| 泗水县| 瑞丽市| 广南县| 炉霍县| 阿鲁科尔沁旗|