main thread wait for all threads which isDeamon() set false end

Viewed 22

I am trying to learn something about Java Thread. I do not set isDeamon(true) for the t1.t2 Threads, but main thread still waits. So I don't know how to explain this. Please give me some help, THX. There is my code:

package runnable;

public class RunnableTest1 {
    public static int flag = 0;


    public static void main(String[] args){
        Thread t1 = new Thread(new NewMyRunnable1("t1"));
        t1.setName("My Test 1");
        System.out.println(t1.toString()+t1.isDaemon());

        Thread t2 = new Thread(new NewMyRunnable1("t2"));
        t2.setName("My Test 2");
        System.out.println(t2.toString()+t2.isDaemon());

        t1.start();
        t2.start();

        System.out.println("main done "+flag);
    }
}

class NewMyRunnable1 implements Runnable {
    private String name = "";

    public static int TIMES = 10;

    public NewMyRunnable1(String name) {
        this.name = name;
    }

    @Override
    public void run() {
        int i = 0;
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        while(i < TIMES){
            System.out.println(name +": "+ i);
            Thread.yield();
            i++;
        }
    }
}
1 Answers

You have two threads, these threads are not demons. Your main thread can't finish before both threads will finish since both threads is not a demon. It's correct behavior. You can set both threads .setDemon(true); and run your program and it will finish without waiting for t1 and t2.

see point 2

Related