歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java中User Thread和Daemon Thread的區別

Java中User Thread和Daemon Thread的區別

日期:2017/3/1 10:24:27   编辑:Linux編程

Java將線程分為User線程和Daemon線程兩種。通常Daemon線程用來為User線程提供某些服務。程序的main()方法線程是一個User進程。User進程創建的進程為User進程。當所有的User線程結束後,JVM才會結束。

通過在一個線程對象上調用setDaemon(true),可以將user線程創建的線程明確地設置成Daemon線程。例如,時鐘處理線程、idle線程、垃圾回收線程、屏幕更新線程等,都是Daemon線程。通常新創建的線程會從創建它的進程哪裡繼承daemon狀態,除非明確地在線程對象上調用setDaemon方法來改變daemon狀態。

需要注意的是,setDaemon()方法必須在調用線程的start()方法之前調用。一旦一個線程開始執行(如,調用了start()方法),它的daemon狀態不能再修改。通過方法isDaemon()可以知道一個線程是否Daemon線程。

通過執行下面的代碼,可以很清楚地說明daemon的作用。當設置線程t為Daemon線程時,只要User線程(main線程)一結束,程序立即退出,也就是說Daemon線程沒有時間從10數到1。但是,如果將線程t設成非daemon,即User線程,則該線程可以完成自己的工作(從10數到1)。

  1. import static java.util.concurrent.TimeUnit.*;
  2. public class DaemonTest {
  3. public static void main(String[] args) throws InterruptedException {
  4. Runnable r = new Runnable() {
  5. public void run() {
  6. for (int time = 10; time > 0; --time) {
  7. System.out.println("Time #" + time);
  8. try {
  9. SECONDS.sleep(2);
  10. } catch (InterruptedException e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. }
  15. };
  16. Thread t = new Thread(r);
  17. t.setDaemon(true); // try to set this to "false" and see what happens
  18. t.start();
  19. System.out.println("Main thread waiting...");
  20. SECONDS.sleep(6);
  21. System.out.println("Main thread exited.");
  22. }
  23. }

  • t為Daemon線程的輸出:

Time #10

Time #9

Time #8

Main thread exited.

Time #7

  • t為User線程的輸出:

Main thread waiting...

Time #10

Time #9

Time #8

Main thread exited.

Time #7

Time #6

Time #5

Time #4

Time #3

Time #2

Time #1

Copyright © Linux教程網 All Rights Reserved