Machine-translated by Google. Questions are authored in English.
Top

Discussion

Sample04 is run - what will be the output?

public class Sample04
{
    public static void main(String[] args)
    {
        Thread t = new Thread(() -> System.out.println("work"));
        t.start();
        t.setDaemon(true);
    }
}

  • A.work only, with no exception
  • B.An IllegalThreadStateException, and work is never printed
  • C.Nothing, because a daemon thread produces no output
  • D.work, and an IllegalThreadStateException in main

Answer: D

setDaemon must be called before the thread is started and throws IllegalThreadStateException if the thread is alive. The worker has already been started, so it runs and prints while main fails on the next line. The two threads are independent, so both effects occur.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.