Hi, I worked on this question from the practice exam:
public class Checkout2 implements Runnable {
void doStuff() { }
synchronized void doSynch() {
try { Thread.sleep(1000); }
catch (Exception e) { System.out.print("e "); }
}
public static void main(
String[] args) {
long start = System.currentTimeMillis();
new
Thread(new Checkout2()).start();
Thread t1 = new Thread(new Checkout2());
System.out.println("What is t1? "+ t1.getId());
t1.start();
try { t1.join(); }
catch (Exception e) { System.out.print("e "); }
System.out.println("elapsed: "
+ (System.currentTimeMillis() - start));
}
public void run() {
for(int j = 0; j < 4; j++) {
doStuff();
System.out.println(Thread.currentThread().getId());
try { Thread.sleep(1000); }
catch (Exception e) { System.out.print("e "); }
doSynch();
} } }
Which are true? (Choose all that apply.)
A. Compilation fails.
B. Elapsed time will be about eight seconds.
C. Elapsed time will be about nine seconds.
D. Elapsed time will be about 12 seconds.
E. Changing doSynch() to be unsynchronized will change elapsed by only a few
milliseconds.
F. Changing doSynch() to be unsynchronized will change elapsed by 450 or more
milliseconds.
The answer is :
Answer (for Objective 4.3):
B and E are correct. Even when doSynch() is synchronized, the two run() invocations
aren’t running against the same Checkout2 object. This code creates two distinct
Checkout2 objects, so there is no synchronization.
A, C, D, and F are incorrect based on the above.
My interpretation is that t1.join means the t1 thread will execute at a certain time and the CPU allocate its resources for t1 until it is done and the other thread will wait until t1 is done.
Therefore, I think the time elapse can be 8 second/thread * 2 thread = 16 seconds. Think of a scenario that t1 execute first and it takes 8 seconds and the other thread execute next and takes another 8 second.
I thought the answer B is not guaranteed.