Posted on 2009-06-02 21:26
啥都寫點(diǎn) 閱讀(278)
評(píng)論(0) 編輯 收藏 所屬分類:
J2SE
關(guān)鍵技術(shù):
- Thread的setDaemon實(shí)例方法設(shè)置線程是否為守護(hù)線程,參數(shù)為true表示該線程為守護(hù)線程。
- 線程被運(yùn)行后,setDaemon實(shí)例方法無效,即必須在調(diào)用start方法之前調(diào)用setDaemon方法,才能設(shè)置線程為守護(hù)線程。
- 程序中啟動(dòng)的線程默認(rèn)為非守護(hù)線程,但在守護(hù)線程中啟動(dòng)的線程都是守護(hù)線程。
- 當(dāng)程序中所有非守護(hù)線程都結(jié)束時(shí),守護(hù)線程無條件地被立即結(jié)束。
package book.thread;
/**
* Daemon(守護(hù))線程
* Daemon線程區(qū)別一般線程之處是:
* 只有虛擬機(jī)中的用戶線程(非Daimon線程)全部結(jié)束,Daemon線程就會(huì)立即結(jié)束,并且也不會(huì)調(diào)用finally里的語句。
* daemon線程所產(chǎn)生的所有線程都是daemon的
*/
public class Daemon {
static class MainThread extends Thread {
public void run() {
System.out.println("MainThread is daemon? " + this.isDaemon());
System.out.println("MainThread begin!");
//啟動(dòng)子線程
Thread sub1 = new SubThread();
//sub1線程為守護(hù)線程
sub1.setDaemon(true);
sub1.start();
try {
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("MainThread" + " finally");
}
System.out.println("MainThread end!");
}
}
static class SubThread extends Thread {
public void run() {
System.out.println("SubThread is daemon? " + this.isDaemon());
System.out.println("SubThread begin!");
int i = 0;
try {
while (i < 10) {
System.out.println("SubThread " + i++);
Thread.sleep(200);
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println("SubThread finally");
}
System.out.println("SubThread end!");
}
}
public static void main(String[] args) {
System.out.println("Main begin!");
//默認(rèn)情況下mainThread是普通線程
Thread mainThread = new MainThread();
//啟動(dòng)mainThread線程
mainThread.start();
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("Main end!");
}
}
--
學(xué)海無涯