CIS 260 daemon threads

Daemon threads are background threads that are considered unimportant enough that the program will terminate if the only threads still running are daemon threads. You can make a thread a daemon thread by calling setDaemon(true) on the thread, and check its state by calling isDaemon().

import java.util.concurrent.locks.*;
import java.util.*;

public class TThreadE {
    public static void main(String[] args) {
        TThreadE app = new TThreadE();
    }
    
    private TThreadE() {
        Random r = new Random();
        for (int i=0; i<10; i++) {
            int time = r.nextInt(20) * 1000;
            if (i == 9) time = 5000;
            DThread t = new DThread(i, time);
            if (i < 9) t.setDaemon(true);
            System.out.println("Thread " + t.getNum() + " (" + t.getTime()/1000 + ") " + (t.isDaemon()?"daemon":""));
            t.start();
        }
        System.out.println("Done spawning threads");
    }

    class DThread extends Thread {
        private int time;
        private int num;
        
        public DThread(int num, int millisecs) { this.num = num; time = millisecs; }
        public int getTime() { return time; }
        public int getNum() { return num; }
        
        public void run() {
            System.out.println("Starting thread " + num);
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                // do nothing
            }
            System.out.println("Ending thread " + num);
        }
    }
}

/*
   Thread 0 (2) daemon
   Thread 1 (16) daemon
   Starting thread 0
   Thread 2 (17) daemon
   Starting thread 1
   Thread 3 (7) daemon
   Starting thread 2
   Thread 4 (15) daemon
   Starting thread 3
   Thread 5 (5) daemon
   Starting thread 4
   Thread 6 (16) daemon
   Starting thread 5
   Thread 7 (6) daemon
   Starting thread 6
   Thread 8 (14) daemon
   Starting thread 7
   Thread 9 (5)
   Starting thread 8
   Done spawning threads
   Starting thread 9
   Ending thread 0
   Ending thread 9
   Ending thread 5
*/

Previous: await and signal

Next: additional threading topics