IntelliJ Java IDE
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread qstn Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Professional Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Thread qstn" Watch "Thread qstn" New topic
Author

Thread qstn

Santosh Jaiswal
Greenhorn

Joined: Oct 04, 2000
Posts: 26
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

Joined: Nov 04, 2000
Posts: 175
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

Joined: Oct 04, 2000
Posts: 26
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

Joined: Nov 04, 2000
Posts: 135
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.
 
 
subject: Thread qstn
 
Threads others viewed
A doubt on Multiple Threads and the "join()" method !!
Thread Problem
Why does Thread.sleep know which thread.....
Thread,Join problem
code for isAlive()
developer file tools