简体   繁体   中英

how can i arrange gui and thread synchronization of gui component's state reading?

I want to ask a question about synch. of gui thread and another thread that reads component's state periodically, say label in Java. Here is the case, I have gui and a thread. And I have a label in gui. I have a thread that periodically (say 100ms) reads that label. I think there occurs a problem when gui changes the label and at the same time thread attempts to read label (concurrentModificationException error). How can I overcome this situtaion?

Unless explicitly otherwise stated in the Javadocs, Swing components (assuming you're talking about Swing) are not thread-safe. They can only be manipulated by the Event Dispatch Thread (EDT).

If you want to manipulate Swing components from another thread, there are several ways you can do it, including SwingUtilities.invokeLater() , SwingUtilities.invokeAndWait() , and SwingWorker (these don't actually manipulate the components from another thread - they just make it easy to coordinate with the EDT).

SwingUtilities.invokeLater() and invokeAndWait() allow you to pass a Runnable to them, and have the Event Dispatch Thread run them for you. The SwingWorker allows you to create a task and divide it into two portions: a portion that is long running and shouldn't be run in the EDT, and a portion with the work to do in the EDT once the background job is complete.

Here's a tutorial on concurrency with Swing . It has all you need to learn about using SwingUtilities and SwingWorker .

Note, however, that Swing components don't do anything to detect (erroneous) multi-threaded access. Swing components don't throw ConcurrentModificationExceptions . If you're getting that, you're either using a Windowing toolkit other than Swing, or it exception is being raised by some other code. (If you're using SWT, have a look at this ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM