Alex Rivera | Logout

How does join() work? (Multithreading in Java)

Asked 2011-02-04T15:14:18.133
12

I'm preparing for an exam and after going over some sample exercises (which have the correct answers included), I simply cannot make any sense out of them.

The question

(Multiple Choice): What are the some of the possible outcomes for the program below?

A) Value is 1. Value is 1. Final value is 1.

B) Value is 1. Value is 1. Final value is 2.

C) Value is 1. Final value is 1. Value is 2.

D) Value is 1. Final value is 2. Value is 2.

The Program

public class Thread2 extends Thread {

    static int value = 0;
    static Object mySyncObject = new Object();

    void increment() {

        int tmp = value + 1;
        value = tmp;

    }

    public void run() {

        synchronized(mySyncObject) {

            increment();
            System.out.print("Value is " + value);

        }

    }

    public static void main(String[] args) throws InterruptedException {

        Thread t1 = new Thread2();
        Thread t2 = new Thread2();

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.print("Final value is " + value);

    }

}

The correct answers are: A), C) and D).

For case A) I don't understand how it's possible that both threads (after incrementing a seemingly static variable from within a synchronized block(!)) end up being set to 1 and the final value is thus 1 as well...?

Case C and D are equally confusing to me because I really don't understand how it's possible that main() finishes before both of the required threads (t1 and t2) do. I mean, their join() methods have been called from within the main function, so to my understanding the main function should be required to wait until both t1 and t2 are done with their run() method (and thus have their values printed)...??

It'd be awesome if someone could guide me through this.

Thanks in advanc

Edit
Report

1 Answer

-2

First i'd like to agree with rlibby. His answer can be proven by writing the program an present the output to the teacher. If we omit that look at this:

  • its guaranteed to have two prints of 'Value is...'
  • it's not possible to print 'Value is 1' twice, since the increment is synchronized by a static object (this eliminates A and B)
  • the order of the print statements can not be forecasted
  • but: if we read a 'Final value is x' there must be a 'Value is X' too, no matter if before or after but it must exist
  • answered 2012-08-21T09:02:23.927

    Your Answer