开发者

Java synchronization question

开发者 https://www.devze.com 2023-03-24 09:18 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消