devxlogo

Multiple Drawing Threads

Multiple Drawing Threads

Question:
I have written an applet which uses a Graphics object to draw movingcircles. 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 curethis?

Answer:
AWT graphics are designed to be drawn all from the same thread. Ifyou attempt to simultaneously draw to components from differentthreads, unpredictable results such as the ones you are seeing willresult.

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

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist