This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Murach's Python Programming and have Michael Urban and Joel Murach on-line!
See this thread for details.
Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

multithread design help  RSS feed

 
Kim Vue
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
-Kim-
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24215
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

  •  
    Marilyn de Queiroz
    Sheriff
    Posts: 9079
    12
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Thread questions are not exactly beginner questions. I'm moving this to the Threads and Synchronization forum.
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!