?? daemon.java
字號:
package book.thread;
/**
* Daemon(守護)線程
* Daemon線程區別一般線程之處是:
* 只有虛擬機中的用戶線程(非Daimon線程)全部結束,Daemon線程就會立即結束,并且也不會調用finally里的語句。
* daemon線程所產生的所有線程都是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!");
//啟動子線程
Thread sub1 = new SubThread();
//sub1線程為守護線程
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!");
//默認情況下mainThread是普通線程
Thread mainThread = new MainThread();
//啟動mainThread線程
mainThread.start();
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("Main end!");
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -