簡體   English   中英

同時創建用戶和守護程序線程不起作用

[英]Creating User and Daemon threads simultaneously not working

我在主要方法t1和t2中創建了兩個線程。 t1是用戶線程,並具有10條打印語句的循環t2是守護程序線程,並具有10條打印語句的循環

main啟動兩個線程並具有單個print語句。 但是,即使在主出口退出之后,t2仍然繼續與t1平行運行。 守護程序線程即使退出創建它的線程也可以運行。

請更新謝謝tejinder

守護程序線程即使退出創建它的線程也可以運行。

是。 守護程序線程將一直運行,直到它退出或所有非守護程序線程完成並且JVM終止為止。 啟動子線程的父線程的操作或終止根本不影響子線程。

如果要停止子線程,則父線程應將其interrupt() ,然后與之join() 就像是:

Thread child = new Thread(new MyRunnable());
child.start();
...
child.interrupt();
child.join();

請記住, interrupt() 不會取消線程。 它只會使諸如Thread.sleep()Object.wait()以及其他方法拋出InterruptedException 您的子線程應執行以下操作:

 while (!Thread.currentThread().isInterrupted()) {
      ...
      try {
          Thread.sleep(100);
      } catch (InterruptedException e) {
          // catching the exception clears the interrupt bit so we need to set it again
          Thread.currentThread().interrupt();
          // we probably want to quit the thread if we were interrupted
          return;
      }
 }

是的,無論您從哪里啟動線程,線程都是獨立運行的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM