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

Discussion

Sample62 is run - what will be the output?

public class Sample62
{
    static int shared = 0;

    static class Job implements Runnable
    {
        int local = 0;

        public void run()
        {
            for (int i = 0; i < 3; i++) { local++; shared++; }
        }
    }

    public static void main(String[] args) throws InterruptedException
    {
        Job job = new Job();
        Thread a = new Thread(job), b = new Thread(job);
        a.start(); a.join(); b.start(); b.join();
        System.out.println(job.local + " " + shared);
    }
}

  • A.3 3
  • B.6 6
  • C.3 6
  • D.6 3

Answer: B

Both threads run the same Job instance, so its field is shared just as the static one is; nothing is copied per thread. Each thread adds three to both, giving six each. Starting the second thread only after joining the first removes any interleaving, so the totals are exact.

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

Post your comment

Please log in or register to post a comment.