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

Discussion

Sample18 is run - what will be the output?

public class Sample18
{
    public static void main(String[] args)
    {
        new Thread(() -> System.out.println("A")).start();
        new Thread(() -> System.out.println("B")).start();
    }
}

  • A.Nothing, because main returns before either thread runs
  • B.A and B in either order, since nothing orders the two threads
  • C.A then B, because the first thread was started first
  • D.B then A, because the second thread is scheduled first

Answer: B

Starting a thread only makes it eligible to run; the scheduler decides when, so neither ordering is promised and the answer is genuinely both. main returning does not stop them, because both are non-daemon threads and the JVM waits for them. Ordering requires join, a lock or a queue.

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

Post your comment

Please log in or register to post a comment.