multithread design help
posted 13 years ago
I have one thread, t1 ,which creates a second thread, t2. Functionality of t1 is to collect data from a file and write them to t2. t2 is of a different Class than t1. t2 handles the data for a specified amount of time. This 'time' need be only a simulated time. My problem is I can't seem to get both threads to share the same time--to increment the same time. I tried having t1 pass t2 the time but t2's incrementation on time doesn't affect t1's time. How could I pass it back? I also tried a separate class to hold the time and have both threads access that class but calling this time class doesn't change the time at all. Actually, the only way that I've been able to change time is having time++; be in the run() of the threads. Might somebody have a suggestion with regards to what I'm doing wrong or what I should try doing? Thank you.
author and iconoclast
posted 13 years ago
There are two different things that could be happening here, and from your message I can't tell which is more likely:
The two threads aren't actually sharing a time variable; you've got two different values of the time. This is more of a fundamental problem with understanding how objects work; if that's the problem, then maybe you could look here and here for some clarification. There's a synchronization problem. Separate threads aren't all guaranteed to see the same value for a given variable until a "memory barrier" forces all threads to "catch up." The reason for this is that modern CPUs cache some of the contents of memory, and each thread may have its own cache which is only periodically reconciled with main memory (this is oversimplifying a little but you get the idea.) You can use the Java "synchronized" keyword to provide a memory barrier; if you use synchronized getTime() and incrementTime() methods to access the time variable, then this problem will go away.
To do a great right, do a little wrong - shakepeare. twisted little ad:
the new thread boost feature: great for the advertiser and smooth for the coderanch userhttps://coderanch.com/t/674455/Thread-Boost-feature