Search code examples
androidmultithreadingspawn

Android daemon thread test


I'm testing Think in Java's Multi thread like this in Android:

private void testDeamon(){

    Thread d = new Daemon();
    System.out.println(
            "d.isDaemon() = " + d.isDaemon());


    try {
        Thread.sleep(2000);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}


public class Daemon extends Thread {
    private static final int SIZE = 10;
    private static final String TAG = null;
    private int i = 9000;

    private Thread[] t = new Thread[SIZE];
    public Daemon() { 
        setDaemon(true);
        start();
    }
    public void run() {
        for(int i = 0; i < SIZE; i++)
            t[i] = new DaemonSpawn(i);
        for(int i = 0; i < SIZE; i++)
            System.out.println(
                    "t[" + i + "].isDaemon() = " 
                            + t[i].isDaemon());
        while(true) {
            Log.d(TAG, "Deamon running..."+ i--);
            if (i==0) 
                break;

            yield();
        }
    }

    class DaemonSpawn extends Thread {
        public DaemonSpawn(int i) {
            System.out.println(
                    "DaemonSpawn " + i + " started");
            start();
        }
        public void run() {
            while(true) 
                yield();
        }
    }
}
  1. Why the spawn daemon's outcome is false, so the spawn of a daemon is not daemon here

  2. Why the Daemon thead keep running after the Android application exit? According to the TIJ, the JVM exit after all non-deamon thread killed and the deamon thread exit too. So the JVM is not shutdown after application destroyed? Thanks.


Solution

  • I can't answer the first question. They should be daemons too (http://www.linuxtopia.org/online_books/programming_books/thinking_in_java/TIJ315_005.htm)
    For Android purposes, daemon threads or non-daemon threads are moot. Your app's process never exits: It either remains in the background or it gets killed at some point.

    Your second question: What do you mean by "... Android application exit..."? Apps don't 'exit', they just go into the background and, if the OS deems it necessary, they may get killed.

    In other words, when your app goes into the background, it doesn't exit. It keeps running in the background (until it gets killed at some point).