• Post Reply Bookmark Topic Watch Topic
  • New Topic

is it good practice to pass thread references across classes?

 
Ajay Xavier
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
consider the following scenario

i have class1 which is creating a instance of a thread but i need to start the thread in another class say in class2

class class1
{

public void mthd1()
{
myRunnable runable = new myRunnable();
Thread t = new Thread(runable);
.
.
new class2(this);

}
.
.
}

class class2()
{
public mthd2()
{
// need to start thread t here
}
}

To start the thread here i need to pass the reference to class2 either in these two way
1. put a getter method in class1 which returns "t" (since class2 has reference to class1) invoke this getter method
2. pass the reference while creating the class2 object

i dont feel both the ways are best practices

is there any better ways to do this?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pass Class2 exactly what it needs. If it needs a Thread, pass it a Thread. If you make it require a Class1 object, nobody can call it without also creating a Class1 object. That may not seem important right now or for this case, but it can be critical to reuse and testing.

On the other hand, let's ask if Class2 really needs t, or maybe we're asking if Class1 really needs t. Can Class2 just get the Runnable as a parameter and create and start the Thread itself?
[ June 02, 2006: Message edited by: Stan James ]
 
Ajay Xavier
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

Due to some reasons class1 has to instantiate thread t and class2 has to start this thread. which one is the best approach to acheive this functionality.


Regards,
Ajay.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
#2 > #1
 
Ajay Xavier
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
#2 > #1


what does this mean?
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ajay Xavier:


what does this mean?


Number 2 is greater than number 1.
 
Edward Harned
Ranch Hand
Posts: 291
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just pass the reference in the constructor:

... new class2(this,t);

It is perfectly acceptable. A reference is just a reference no matter what it is for.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!