简体   繁体   中英

Java synchronization question

Just seeking some confirmation on something:

I have a server object with Swing GUI, containing a method handle() , which is accessed by external threads, and another method doThis() , which is run from the server object's GUI.

I understand that Swing event handling takes place on the event dispatch thread, so it's actually the event dispatch thread that accesses doThis() .

There is a possibility that doThis() and handle() will result in interference. To avoid that, I should make both methods synchronized right? This will prevent the event dispatch thread and the other external threads from calling one method before the other is completed.

Is my reasoning correct?

Instead, use SwingWorker ; TwoRoot is a simple example. Put handle() in the background and doThis() in process() .

From the Java tutorial on synchronization :

making these methods synchronized has two effects: First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object. Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

So yes.

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