dcsimg
Passing variables from main thread to child thread so that child thread can keep a saperate copy of it.
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   abhishek_dwivedi
Posted On:   Friday, November 10, 2006 12:36 PM

In my program, I have a non-ending thread(infinite loop), which keeps creating other threads(which ends) in each loop. These child thread's life time is 3rd party dependent. Hence one can end in few seconds and one can last upto 1/2 hour. In non-ending main thread I have 3 String variable, whose values should be passed to child threads at creation time and they should be able to keep that value(unchanged) with them till they finish, as parent(non-ending) thread will keep changing values of these variables in every loop. Here I am writing psuedo code to help you understand it better. Please come up with some solution. I am not sure about how to use ThreadLocal variable. //main thread for(;;){ String s1 = //assign some value   More>>

In my program, I have a non-ending thread(infinite loop), which keeps creating other threads(which ends) in each loop. These child thread's life time is 3rd party dependent. Hence one can end in few seconds and one can last upto 1/2 hour. In non-ending main thread I have 3 String variable, whose values should be passed to child threads at creation time and they should be able to keep that value(unchanged) with them till they finish, as parent(non-ending) thread will keep changing values of these variables in every loop. Here I am writing psuedo code to help you understand it better. Please come up with some solution. I am not sure about how to use ThreadLocal variable.



			
//main thread
for(;;){
String s1 = //assign some value
String s2 = //assign some value
String s3 = //assign some value
new Thread(new Runnable(){
public void run(){
//This part uses s1,s2,s3. And may take hours to finish.
//By that time s1,s2,s3 are changed in next looping of
//main thread.

}
}).start();
}//for loop ends here.
   <<Less

Re: Passing variables from main thread to child thread so that child thread can keep a saperate copy of it.

Posted By:   Robert_Lybarger  
Posted On:   Friday, November 10, 2006 07:14 PM

Instead of having an anonymous Runnable instance, could you create an actual class which implements the Runnable, has a constructor to save a local copy of info passed in at initialization time, contains a private Thread object, and otherwise provides some delegate methods for that Thread object? For example:

class FooRunnable implements Runnable {
private String myString;
private Thread thread;

FooRunnable(String someString) {
myString = new String(someString);
thread = new Thread(this);
}

public void start() {
thread.start();
}

public void run() {
/* whatever needs to happen */
}

/* other delegates if/as needed */
}

??

About | Sitemap | Contact