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

Discussion

Sample82 is run - what will be the output?

public class Sample82
{
    public static void main(String[] args) throws InterruptedException
    {
        Runnable job = () -> System.out.print(Thread.currentThread().getName() + " ");
        Thread a = new Thread(job, "one");
        Thread b = new Thread(job, "two");
        a.start(); a.join();
        b.start(); b.join();
    }
}

  • A.main main
  • B.one two
  • C.two one
  • D.Thread-0 Thread-1

Answer: B

Correct answer: one two

A name passed to the Thread constructor replaces the default Thread-N, and getName called inside run returns the name of the thread executing it - not of main. The join after each start makes the order deterministic: thread “one” runs to completion before “two” is started, so the output is one two every time.

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

Post your comment

Please log in or register to post a comment.