Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: User Interface Design
Expertise: Beginner
May 5, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Multiple Drawing Threads

I have written an applet which uses a Graphics object to draw moving circles. However, when multiple threads accesses the same Graphics object, the circles disappear after being on screen for around 5 seconds, without throwing an exception. Why does this happen and how do I cure this?

AWT graphics are designed to be drawn all from the same thread. If you attempt to simultaneously draw to components from different threads, unpredictable results such as the ones you are seeing will result.

Therefore, to ensure predictable behavior you must either use SwingUtilities.invokeLater() to schedule the drawing to occur within the main AWT thread, or properly synchronize your threads. In your case, it may suffice to synchronize access to the Graphics object to ensure that all drawing operations are performed atomically.

DevX Pro
Thanks for your registration, follow us on our social networks to keep up-to-date