Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Thread taking turns  RSS feed

 
Paul Rane
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I'm just learning about threads and have a problem. My program has a thread that computes values in a loop. For each iteration I want a paintComponent() method to be called. The computed values will determine what is drawn. So, I want the program to: compute values and draw, compute values and draw, etc.

Right now I call repaint() and sleep() in the loop. How can I be guaranteed that the paintComponent() method is called before the next values are computed? I've never seen the program not work, but it seems to me that paintComponent() may not run for each value computed.

Thanks
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could try synchronization.
 
Paul Rane
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the idea of what I have right now.



How do I synchronize methods from two different objects? Hope this isn't a stupid question.
 
Jeff Bosch
Ranch Hand
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may also want to investigate join, but synchronization is probably the way you want to go. With synchronization, you can lock an object in one thread or method, then have other objects wait if the object is locked.
 
Jayesh Lalwani
Ranch Hand
Posts: 502
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, No, join will wait for the thread to die. This is a classic publisher-subscriber problem. Assuming data is an object that is shared between the 2 threads



Please note that in this way, your computations will hold up repainting of the screen, and screen repainting will hold up computations. If you want your screen to refresh quickly, or if you want real-time computations, you might want to think about double-bufferring your data. That way, you can take your computation logic out of the synchronized block
 
Paul Rane
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everybody. I think I understand it now.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Moving to Threads and Synchronization...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!