wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Please explain this code Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Please explain this code" Watch "Please explain this code" New topic
Author

Please explain this code

Ankith suresh
Ranch Hand

Joined: Jun 07, 2007
Posts: 42
class RunnableThread implements Runnable {
public void run(){
for (int i = 0;i<100;i++){
System.err.println((Thread.currentThread()).getName());
try{
(Thread.currentThread()).join();
}catch(Exception e){}
}
}

}
class MyThreadTest
{
public static void main(String[] args)
{
RunnableThread r= new RunnableThread();
Thread t1= new Thread(r);
Thread t2= new Thread(r);
Thread t3= new Thread(r);
t1.start();
t2.start();
t3.start();

/*try{
//t1.join();
//t2.join();
// t3.join();
}catch(InterruptedException e){
} */

System.err.println("in main");
}
}


I am getting this output.

---------- intepreter ----------
in main
Thread-0
Thread-1
Thread-2
Manfred Klug
Ranch Hand

Joined: Jun 04, 2007
Posts: 377
Hi Ankith,

have a look at the following statement:

(Thread.currentThread()).join();
Eega Sudheer
Greenhorn

Joined: Jun 12, 2007
Posts: 3
Hi Ankith,

(Thread.currentThread()).join(); Here you are adding calling thread(t1) to running thread(t1)

A thread cannot join itself because this would cause a deadlock.


/*try{
//t1.join();
//t2.join();
// t3.join();
}catch(InterruptedException e){
} */

In the above statements you are adding child threads(t1,t2,t3) to the main thread ie calling thread(main)
Manfred Klug
Ranch Hand

Joined: Jun 04, 2007
Posts: 377
Originally posted by Eega Sudheer:
A thread cannot join itself because this would cause a deadlock.


Your statement is true and false at the same time.

For this example, it is true that the join results in a deadlock. It is false that this will always result in a deadlock.

Syed Salman Ahmad
Greenhorn

Joined: Apr 03, 2007
Posts: 14
If a thread joins itself then it creates a deadlock, so in the code the thread t1 prints its name and then goes into deadlock, similar thing happens to t2 and t3, thats the reason Thread-0, Thread-1 and Thread-2 are printed.
If you run the code in eclipse you will see that the JVM will keep running after you run this code which depicts that deadlock has occurred.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Please explain this code