国产探花免费观看_亚洲丰满少妇自慰呻吟_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ā)表
主站蜘蛛池模板: 静海县| 即墨市| 遵化市| 长岭县| 铜梁县| 浮山县| 和林格尔县| 贡山| 和龙市| 麦盖提县| 綦江县| 拉萨市| 阳曲县| 涟水县| 邵东县| 西华县| 洪江市| 澄迈县| 深圳市| 四川省| 合川市| 新余市| 绍兴市| 斗六市| 沾化县| 宁陕县| 寿宁县| 都安| 崇明县| 马山县| 赫章县| 邹城市| 禄丰县| 潞西市| 桑植县| 杨浦区| 广西| 平原县| 怀化市| 金沙县| 车致|