简体   繁体   中英

Thread deadlocking and synchronization

I know that I need to use synchronization appropriately in order to avoid deadlocking when using multiple threads, but I was wondering:

Do I need to synchronize for both amending the value of and examining a variable, or do I just need to synchronize when I amend the value, but not when I examine the variable?

As for the deadlocking: Darkhogg already correctly pointed out that deadlocking is a result from incorrect synchronization and workflow.

Synchronizing state modifications and state observation: Yes, you need to synchronize both. The effect of the object lock you obtain when entering a synchronized method is that no other thread my enter the same or another synchronized code block that requires the same object lock (synhronizes on the same object). That said, if you do not synchronize the code that observes the state of your object, then this code might be executed concurrently to the synchronized code that modifies the state and you may read an invalid object state.

阅读该文章后,我将为您提供有关同步的更好的知识库http://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html

如果您拥有的资源不是线程安全的,则需要保护检查和修改其值。

as Darkhogg mentioned synchronization causes deadlocks if not used properly.

You need to synchronize code blocks on a data members that are updating(changing data members) the value and can be executed by multiple thread.

Make it synchronized will insure that the data members will not be updated simultaneously.

Synchronized do not use to avoid deadlock

Synchronize keyword ensure thread safely in multithreading environment. Though you have a multi thread, you want to amending and examining member variables.

To do it create a class which contains data variables that you want to thread safed. create synchronized function for appending and examining variables.

class exam
{
 ....

 synchronized void examine()
 {}


 synchronized void amending()
 {}


}

create a single object of the class and pass it to your all thread.

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