標籤:catch read cep down gpo mon rac try 0ms
java線程分兩種:使用者線程和daemon線程。daemon線程或進程就是守護線程或者進程,但是java中所說的daemon線程和linux中的daemon是有一點區別的。
linux中的daemon進程實際是指運行在後台提供某種服務的進程,例如cron服務的crond、提供http服務的httpd;而java中的daemon線程是指jvm執行個體中只剩下daemon的時候,jvm就會退出。
我們通過以下實驗來看下daemon線程和普通使用者線程的區別
- 建立一個運行死迴圈的daemon線程,主線程運行5s後退出,daemon線程也會退出。
public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new MyThread()); thread.setDaemon(true); // 設定線程為daemon線程 thread.start(); Thread.sleep(5000); // 5s後主線程退出 } static class MyThread implements Runnable { @Override public void run() { while (true) { // 線程死迴圈 try { // 100ms 列印一次hello Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("hello"); } } }
運行結果:5ms daemon線程退出。
hellohellohellohellohellohellohellohellohellohellohelloProcess finished with exit code 0
注釋掉daemon,使得線程成為一個普通的使用者線程
public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new MyThread()); // thread.setDaemon(true); // 普通的使用者線程 thread.start(); Thread.sleep(5000); // 5s後主線程退出}static class MyThread implements Runnable { @Override public void run() { while (true) { // 線程死迴圈 try { // 100ms 列印一次hello Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("hello"); } }}
運行結果:線程在主線程運行完後不會退出,一直死迴圈
JAVA DAEMON線程的理解