您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關Java中如何使用守護線程,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
一 點睛
針對守護線程,只要有一個用戶線程在執行,這個進程就不會結束。
當線程中只剩下守護線程時,JVM會自動退出,反之,如果還有其他任何用戶線程存在,JVM都不會退出。
二 代碼
public class ThreadDaemon{ public static void main( String args[] ) { ThreadTest t = new ThreadTest(); Thread tt = new Thread( t ); tt.setDaemon( true ); // 設置后臺運行 tt.start( ); try { // 睡眠1毫秒,避免可能出現的沒有輸出的現象 Thread.sleep( 1 ); } catch( InterruptedException e ) { e.printStackTrace(); } }}class ThreadTest implements Runnable{ public void run() { for( int i = 0; true; ++i ) { System.out.println( i + " " + Thread.currentThread().getName() + " is running." ); } }}
三 運行
0 Thread-0 is running.1 Thread-0 is running.2 Thread-0 is running.3 Thread-0 is running.4 Thread-0 is running.5 Thread-0 is running.6 Thread-0 is running.7 Thread-0 is running.8 Thread-0 is running.9 Thread-0 is running.10 Thread-0 is running.11 Thread-0 is running.12 Thread-0 is running.13 Thread-0 is running.14 Thread-0 is running.15 Thread-0 is running.16 Thread-0 is running.17 Thread-0 is running.18 Thread-0 is running.19 Thread-0 is running.20 Thread-0 is running.21 Thread-0 is running.22 Thread-0 is running.23 Thread-0 is running.24 Thread-0 is running.25 Thread-0 is running.26 Thread-0 is running.27 Thread-0 is running.28 Thread-0 is running.
看完上述內容,你們對Java中如何使用守護線程有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。