• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Question on Threads

 
Shubha Kirani
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the below code, given answer as:
"other.join attempts to join two Threads" ... Please explain.

public class ThreadTest {

class InnerRun implements Runnable {
public void run() {
// do slow stuff
System.out.println ("Ren");
}
}
class InnerRunTwo implements Runnable {
Thread other;
InnerRunTwo(Thread t) {other = t;}
public void run() {
other.join();
System.out.println ("Stimpy");
}
}
void start() {
InnerRun ir = new InnerRun();
Thread t = new Thread(ir);
InnerRunTwo irr = new InnerRunTwo(t);
Thread h = new Thread(irr);
t.start();
h.start();
}
public static void main(String[] args) {
ThreadTest tt = new ThreadTest();
tt.start();

}

}
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Subha,

Welcome to JavaRanch!



class InnerRunTwo implements Runnable {
Thread other;
InnerRunTwo(Thread t) {other = t;}
public void run() {
other.join(); //LINE 1
System.out.println ("Stimpy");
}
}


You should read Line #1 in the way: the current thread joins other thread.
It means current thread can't complete until the thread it joins to
completes.

[EDIT]
Note:
join() throws InterruptedException, so handle that exception.


Thanks,
[ June 13, 2007: Message edited by: Chandra Bhatt ]
 
Pravin Jain
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Note: join() throws IllegalStateException, so handle that exception.


it actually throws InterruptedException and not IllegalStateException
and you need to handle in the run method.
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ooops!!!

It is InterruptedException!

"Previous post edited"

Thanks,
 
Shubha Kirani
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Chandra and Pravin.
Regarding the question, this is from Kathy & Bert, Master Exam. If I enclose 'other.join' in try-catch block (handle InturreptedException), code would compile fine. As explained in the answer key, I did not understand the meaning of 'attempts to join two threads' as there are only two threads. Other two similar program solution say, one thread join after other. SO wanted to know if I'm missing something here.

I wonder the # of posts answered everyday in this website. I'm very new to Java and Ranch. Like to start my career in Java, starting with SCJP certification. Hope one day I get to answer others quiries.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic