Question:
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?
Answer:
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.