Heim  >  Artikel  >  Java  >  Was ist das Konzept des Java-Daemon-Threads?

Was ist das Konzept des Java-Daemon-Threads?

WBOY
WBOYnach vorne
2023-05-01 18:07:13709Durchsuche

1. Wenn andere Nicht-Daemon-Threads abgeschlossen sind, beendet sich der Daemon-Thread von selbst.

2. Jeder Thread kann ein Daemon-Thread werden. Deklarieren Sie einen Thread als Daemon-Thread, indem Sie Thread.setdaemon() aufrufen. Die Gemeinsamkeit von Threads besteht darin, dass sie nur dann Sinn machen, wenn Nicht-Daemon-Threads noch funktionieren.

Instanz

/**
 * 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);
    }
}

Das obige ist der detaillierte Inhalt vonWas ist das Konzept des Java-Daemon-Threads?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Stellungnahme:
Dieser Artikel ist reproduziert unter:yisu.com. Bei Verstößen wenden Sie sich bitte an admin@php.cn löschen