ホームページ  >  記事  >  Java  >  Javaデーモンスレッドの概念とは何ですか

Javaデーモンスレッドの概念とは何ですか

WBOY
WBOY転載
2023-05-01 18:07:13709ブラウズ

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 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。