1、當其他非守護線程完成時,守護線程將自行結束。
2、任何執行緒都可以成為守護線程。透過呼叫Thread.setdaemon()來宣告一個執行緒是一個守護線程。線程的共通點是只有在非守護線程還在工作時才有意義。
實例
/** * Creates ten threads to search for the maximum value of a large matrix. * Each thread searches one portion of the matrix. */ public class TenThreads { private static class WorkerThread extends Thread { int max = Integer.MIN_VALUE; int[] ourArray; public WorkerThread(int[] ourArray) { this.ourArray = ourArray; } // Find the maximum value in our particular piece of the array public void run() { for (int i = 0; i < ourArray.length; i++) max = Math.max(max, ourArray[i]); } public int getMax() { return max; } } public static void main(String[] args) { WorkerThread[] threads = new WorkerThread[10]; int[][] bigMatrix = getBigHairyMatrix(); int max = Integer.MIN_VALUE; // Give each thread a slice of the matrix to work with for (int i=0; i < 10; i++) { threads[i] = new WorkerThread(bigMatrix[i]); threads[i].start(); } // Wait for each thread to finish try { for (int i=0; i < 10; i++) { threads[i].join(); max = Math.max(max, threads[i].getMax()); } } catch (InterruptedException e) { // fall through } System.out.println("Maximum value was " + max); } }
以上是java守護線程的概念是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!