• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Tough Thread question

 
Shiwani Aggarwal
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A implements Runnable {
public void run() {System.out.print(Thread.currentThread().getName());}
}
class B implements Runnable {
public void run() {
new A().run();
new Thread(new A(),"T2").run();
new Thread(new A(),"T3").start();
}
}
class C {
public static void main (String[] args) {
new Thread(new B(),"T1").start();
}
}
Can any one help me understand what is happening in this code> and waht will be output?
 
Dhanashree Mankar
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Preeti:
class A implements Runnable {
public void run() {System.out.print(Thread.currentThread().getName());}
}
class B implements Runnable {
public void run() {
new A().run();
new Thread(new A(),"T2").run();
new Thread(new A(),"T3").start();
}
}
class C {
public static void main (String[] args) {
new Thread(new B(),"T1").start();
}
}
Can any one help me understand what is happening in this code> and waht will be output?


here first in the main method object of thread class ic created by passing an object of runnable interface which is of class B and thread name.
then start method is invoked. now method ckecks class of current object while running. so it will call run method in B.
Now in B again run method in A is called with same thread.now again run method is called but as i said run method doesn't create new thread so with same thread run method in A is called i.e. with T1 thread.
then again start method is called so this time it will create new thread.
i.e. T3 and then it will call run method in class A
 
Dhanashree Mankar
Ranch Hand
Posts: 123
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Preeti:
class A implements Runnable {
public void run() {System.out.print(Thread.currentThread().getName());}
}
class B implements Runnable {
public void run() {
new A().run();
new Thread(new A(),"T2").run();
new Thread(new A(),"T3").start();
}
}
class C {
public static void main (String[] args) {
new Thread(new B(),"T1").start();
}
}
Can any one help me understand what is happening in this code> and waht will be output?

so here ur output will be
T1T1T3
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic