• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread qstn

 
Santosh Jaiswal
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class NewThread implements Runnable {
String name;
Thread t;
NewThread(String Threadname) {
name = Threadname;
t = new Thread(this, name);
t.start();
}

public void run() {
try {
for(int i =5; i >0; i--) {
System.out.println("Child thread:" +i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println(name + "Child thread interrupted" );
}
System.out.println(name +"Exiting Child thread ");
}
}

class DemoJoin {
public static void main(String args[]) {
NewThread ob1 = new NewThread("One"); // create a new thread
NewThread ob2 = new NewThread("two");
try {

System.out.println("waiting for other thread to end");
ob1.t.join();
ob2.t.join();
} catch (InterruptedException e) {
System.out.println("Main thread interrupted" );
}
System.out.println("Exiting Main thread ");
}
}
In the try block, Why ob1.t.join(); instead of ob1.join(); ?
 
Sasikanth Malladi
Ranch Hand
Posts: 175
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have ob1.t.join() and ob2.t.join() as these are 2 different
objects with the same vars t. You spawn a new thread by having a thread var in a class that extends Thread or implements Runnable and then calling the start() method on that thread variable. So you need to call the join() method on the thread and not the object.
 
Santosh Jaiswal
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for prompt reply.
Object ob1 and ob2 are not itself thread ? I getting your point little bit. Can you or anyone else explain in more detail.
It is giving error "undefined variable, class, package" when I write as
t.ob1.join()
??
 
Nasir Khan
Ranch Hand
Posts: 135
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
t.ob1.join() would mean ob1(which refers to Newthread) belongs
to class "t" which is wrong.
Infact "t" is an object of Newthread class so
ob1.t.join() means call join() on "t" of ob1(Newthread).
Anyone correct me if my explaination is wrong.
Nasir Khan.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic