简体   繁体   English

线程死锁和同步

[英]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. 至于死锁:Darkhogg已经正确指出死锁是由于不正确的同步和工作流导致的。

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. 正如Darkhogg提到的,如果使用不正确,同步会导致死锁。

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. Synchronize关键字可确保在多线程环境中安全地运行线程。 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. 创建该类的单个对象,并将其传递给您的所有线程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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