• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question about the join method in Thread

 
Helen Ma
Ranch Hand
Posts: 451
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Helen Ma
Ranch Hand
Posts: 451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I thought about this question myself for a while. I guess the two threads can sleep at the same time and wake up at the same or more or less the same time.
 
Wu Wen
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
t1.join() means current thread will join after t1 completes, and current thread is the main thread, no the other thread Checkout2.

 
O. Ziggy
Ranch Hand
Posts: 430
Android Debian VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How can you make t1 join onto the other thread? (assume the other thread is declared as t2)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic