• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Please explain this code

 
Ankith suresh
Ranch Hand
Posts: 42
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 377
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ankith,

have a look at the following statement:

(Thread.currentThread()).join();
 
Eega Sudheer
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 377
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic