Java中線程分為兩種類型:用戶線程和守護(hù)(服務(wù))線程。通過Thread.setDaemon(false)設(shè)置為用戶線程;通過Thread.setDaemon(true)設(shè)置為守護(hù)線程;不設(shè)置則默認(rèn)為用戶線程。

結(jié)束單線程用 Thread.interrupt() 方法,多線程結(jié)束則需要設(shè)置守護(hù)線程。當(dāng)不存在用戶線程時,守護(hù)線程就會全部終結(jié)(可以理解為:守護(hù)線程是服務(wù)線程,用戶線程是被服務(wù)線程,用戶線程(被服務(wù)線程)全都沒有了,服務(wù)線程便沒有存在意義而自動終結(jié))
例子:
class StopThread implements Runnable {
public void run() {
// 構(gòu)造函數(shù),實例化時默認(rèn)執(zhí)行
while (true) {
// 永真循環(huán),用于檢測該守護(hù)線程會不會自動結(jié)束
System.out.println(Thread.currentThread().getName() + "....run");
}
}
}
public class threadTest {
public static void main(String[] args) {
StopThread st = new StopThread();
Thread t1 = new Thread(st);
// 創(chuàng)建新線程
Thread t2 = new Thread(st);
t1.setDaemon(true);
// 設(shè)置成守護(hù)(服務(wù))線程,當(dāng)用戶線程全掛時,所有守護(hù)線程也跟著掛
t2.setDaemon(true);
t1.start();
// 線程開始
t2.start();
int num = 0;
while (true) {
if (num++ == 10) {
break;
}
System.out.println(Thread.currentThread().getName() + "......." + num);
}
System.out.println("over");
}
}
本文題目:Java語言多線程終止中的守護(hù)線程實例-創(chuàng)新互聯(lián)
標(biāo)題鏈接:http://www.chinadenli.net/article30/djhoso.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、外貿(mào)建站、網(wǎng)站改版、App設(shè)計、搜索引擎優(yōu)化、動態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)