简体   繁体   English

主线程等待所有线程 isDeamon() 设置假结束

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

I am trying to learn something about Java Thread.我正在尝试了解有关 Java 线程的知识。 I do not set isDeamon(true) for the t1.t2 Threads, but main thread still waits.我没有为 t1.t2 线程设置 isDeamon(true),但主线程仍在等待。 So I don't know how to explain this.所以我不知道如何解释这个。 Please give me some help, THX.请给我一些帮助,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++;
        }
    }
}

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);您可以设置两个线程.setDemon(true); and run your program and it will finish without waiting for t1 and t2.并运行你的程序,它会在不等待 t1 和 t2 的情况下完成。

see point 2见第2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM