• Post Reply Bookmark Topic Watch Topic
  • New Topic

how to call a method based on the thread name??

 
aresh babu
Ranch Hand
Posts: 65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI

i have requirement that i have to call a method based on the thread name. I was trying to do in the following way.
class ThreadShare extends Thread{
public static void main(String args[]){
ThreadShare thread1= new ThreadShare();
thread1.setName("thread1");
ThreadShare thread2= new ThreadShare();
thread2.setName("thread2");
thread1.start();
thread2.start();
}
public void run(){
if(Thread.currentThread.getName().equals("thread1")){
method1();
}
if(Thread.currentThread.getName().equals("thread2")){
method2();
}
}
}
If i do in this way i am able to call method1() only.
If i interchange calls
thread2.start();
thread1.start();
then i am able to call method2() only
But i want to call both the methods based on the thread name.
Can any one please let me know how to call both methods based on the thread name??


Thanks in advance
Aresh Babu
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For starters, you most likely shouldn't extend Thread, you should implement Runnable: ExtendingThreadVsImplementingRunnable

Why don't you pass a parameter in the ThreadShare constructor that tells the run method what to do?
 
saxena ashish
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just ran your code and it worked fine for me. What are you trying to do in your method1/2?
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!