Reputation: 6136
I have that code:
Main class:
public class myTest {
public static void main(String[] args) {
try {
Thread t1 = new Thread(new myThreadClass("thread 1"), "thread 1");
t1.start();
} catch (UnknownHostException ex) {
Logger.getLogger(glownyTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(glownyTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
My Thread class
public class myThreadClass extends Thread {
private HashSet<String> texts = new HashSet<String>();
public myThreadClass(String id) throws UnknownHostException, IOException {}
@Override
public void run() {
... collecting Strings into my hashSet ....
}
public HashSet<String> getTexts() {
return texts;
}
}
I've tried to call
t1.getTexts();
in my Main Class after starting the thread, but it doesn't work - I want to access texts hashSet from my Main Class level. How to achieve it?
Upvotes: 1
Views: 1492
Reputation: 2758
myThreadClass t1 = new myThreadClass("thread 1");
t1.start()
try{
t1.join();
t1.getTexts();
}catch(InterruptedException x){
....
}
Usually the first letter of the class name is capital.
Upvotes: 0
Reputation: 20442
If you are trying to access a method belonging to your type myThreadClass
then you need to be sure to declare the variable as an instance of that type.
Like so:
myThreadClass t1 = new myThreadClass("thread 1");
There are some problems you are likely to run into ... like needing to join
the Thread
to be sure that it finishes populating the HashSet
.
Upvotes: 1
Reputation: 116
You can either create reference of myThreadClass
myThreadClass t1
or
cast your reference to myThreadClass like
((myThreadClass )t1).getTexts();
This will work!!
Upvotes: 0
Reputation: 200158
Do not abuse the Thread
class for your program logic. You should build your custom Runnable
implementation, which you pass into Thread
's constructor. That way the separation of concerns between thread control and your program logic will be more apparent to you.
Upvotes: 0