java中线程setDeaemon的混乱

发布于 2024-11-02 08:42:45 字数 1578 浏览 1 评论 0原文

根据java当setDaemon设置为true时

它不会阻止 JVM 程序完成时退出,但是 线程仍在运行。一个 守护线程的示例是 垃圾收集。

从下面的代码示例来看,当setDaemon设置为true时,主线程创建的线程将停止执行,实际上它应该继续运行。当setDaemon设置为false时,即使主线程退出,子线程也会打印i的值。 请澄清我的疑问。

public class DeamonSample implements Runnable
{
      public void run()
      {
            try 
{
System.out.println("T1 started...");

                  for (int i=0;i<1000;i++)
                  {
                        TimeUnit.SECONDS.sleep(1);
                        System.out.print(i+" ");
                  }
            } 
            catch (InterruptedException e) 
            {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
            finally
            {
                  System.out.println("T1 ended...");
            }

      }


      /**
      * @param args
      */
      public static void main(String[] args)
      {
            // TODO Auto-generated method stub
            System.out.println("Main Started...");
            System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
            DeamonSample deamonSample=new DeamonSample();
            Thread t1=new Thread(deamonSample);
            t1.setDaemon(true);
            t1.start();
            System.out.println("T1 Type="+t1.isDaemon());
            System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
            System.out.println("Main ended...");
      }

}

According to java when setDaemon is set to true

it does not prevent the JVM from
exiting when the program finishes but
the thread is still running. An
example for a daemon thread is the
garbage collection.

From the following code sample , the thread created by main thread stops executing when setDaemon is set to true, actually it should keep on running . when setDaemon is set false the child thread print value of i even though main thread exited.
kindly clarify my doubt.

public class DeamonSample implements Runnable
{
      public void run()
      {
            try 
{
System.out.println("T1 started...");

                  for (int i=0;i<1000;i++)
                  {
                        TimeUnit.SECONDS.sleep(1);
                        System.out.print(i+" ");
                  }
            } 
            catch (InterruptedException e) 
            {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
            }
            finally
            {
                  System.out.println("T1 ended...");
            }

      }


      /**
      * @param args
      */
      public static void main(String[] args)
      {
            // TODO Auto-generated method stub
            System.out.println("Main Started...");
            System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
            DeamonSample deamonSample=new DeamonSample();
            Thread t1=new Thread(deamonSample);
            t1.setDaemon(true);
            t1.start();
            System.out.println("T1 Type="+t1.isDaemon());
            System.out.println("Main Thread Type="+Thread.currentThread().isDaemon());
            System.out.println("Main ended...");
      }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

開玄 2024-11-09 08:42:45

默认情况下,线程不是守护线程。如果您使用任何不是守护进程的线程到达主程序的末尾,那么该进程将继续运行。通过调用 setDaemon(true) ,您可以告诉 JVM 您的线程不应在 main 结束时阻止关闭。

By default threads are not daemon threads. If you get to the end of your main with any thread that's not a daemon then the process will keep running. By calling setDaemon(true) you're telling the JVM that your thread shouldn't block shutdown at the end of main.

别靠近我心 2024-11-09 08:42:45

当执行 t1.setDaemon(true); 时,DeamonSample 实例肯定不会停止;你看到的不确定性来自于印刷品。字符在合并到单个流之前会被写入线程本地缓冲区。

这是一些代码来说明。两个线程轮流递增计数器并打印其状态,但您看到的数字可能非常乱序。

import java.util.concurrent.atomic.AtomicInteger;

public class FunnyPrinter extends Thread {
    static AtomicInteger counter = new AtomicInteger(0);

    int parity;

    public FunnyPrinter(int parity) {
        super();
        this.parity = parity;
    }

    public void run() {
        for (;;)
            if (counter.intValue() % 2 == parity)
                System.out.println(counter.incrementAndGet());
    }

    public static void main(String[] args) {
        FunnyPrinter t1 = new FunnyPrinter(0), t2 = new FunnyPrinter(1);
        t1.start(); t2.start();
    }
}

如果您需要确定性,请在 System.out 上进行同步,并在块结束之前刷新它。

The DeamonSample instance is assuredly not stopped when t1.setDaemon(true); is executed; the nondeterminism that you see comes from the prints. Characters are written to thread-local buffers before they are merged into a single stream.

Here's a bit of code to illustrate. Two threads take turns incrementing a counter and printing its state, but the numbers you see may be very much out of order.

import java.util.concurrent.atomic.AtomicInteger;

public class FunnyPrinter extends Thread {
    static AtomicInteger counter = new AtomicInteger(0);

    int parity;

    public FunnyPrinter(int parity) {
        super();
        this.parity = parity;
    }

    public void run() {
        for (;;)
            if (counter.intValue() % 2 == parity)
                System.out.println(counter.incrementAndGet());
    }

    public static void main(String[] args) {
        FunnyPrinter t1 = new FunnyPrinter(0), t2 = new FunnyPrinter(1);
        t1.start(); t2.start();
    }
}

If you need determinism, synchronize on System.out and flush it before the end of the block.

守护在此方 2024-11-09 08:42:45

从下面的代码示例中,当 setDaemon 设置为 true 时,主线程创建的线程停止执行

这不会发生。再次检查你的输出。您的输出将包含以下几行:

Main Started...
主线程类型=false
T1 类型=true
主线程类型=false
主线结束...

..实际上它应该继续运行。

作为守护线程,它不会。由于所有非守护线程(主线程)都已完成,因此 jvm 将退出。

当 setDaemon 设置为 false 时,即使主线程退出,子线程也会打印 i 的值。请澄清我的疑问。

正确的

From the following code sample , the thread created by main thread stops executing when setDaemon is set to true

This will not happen. Check your output again. Your output will contain the following lines:

Main Started...
Main Thread Type=false
T1 Type=true
Main Thread Type=false
Main ended...

..actually it should keep on running .

Being a daemon thread, it wont. Since all non-daemon threads (main) have finished, the jvm will exit.

when setDaemon is set false the child thread print value of i even though main thread exited. kindly clarify my doubt.

Correct

ㄖ落Θ余辉 2024-11-09 08:42:45

在守护线程打印出所有数字之前,主线程终止...
如果你的新线程 isDaemon = true,请在启动线程 () 后尝试此行:

...
Thread t1=new Thread(deamonSample);
try{
   t1.join();
}catch(InterruptedException ie){
    ie.printStackTrace();
}
...

你会看到,守护线程将结束...(至少,这不再是多线程,但该示例是仅用于澄清目的)

The main-thread terminates, before your daemon-thread can print out all your numbers...
if your new thread isDaemon = true, try this line after starting the thread ():

...
Thread t1=new Thread(deamonSample);
try{
   t1.join();
}catch(InterruptedException ie){
    ie.printStackTrace();
}
...

you will see, the daemon-thread will come to an end... (at least, that wouldn´t be multithreading anymore, but that example is for clarifying purpose only)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文