我知道 synchronized 关键字,但我想确保我有一个清晰的理解。
因此,如果我不使用 synchronized 关键字,一个实例变量可能会被两个线程覆盖,但如果我使用 synchronized 关键字,则一次只能有一个线程进入该方法。对吧?
最佳答案
如果两个线程进入一个非同步的方法并更新一些共享状态,那么它会导致不一致。
public synchronized void method(){
//only one thread will be able to enter (IF SAME INSTANCE)
}
但它也建立了一个发生在的关系。这是多线程的可见性部分。
Two actions can be ordered by a happens-before relationship. If one action happens-before another, then the first is visible to and ordered before the second.
Happens-before JLS.
关于java - java中默认可以并发执行实例方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14534701/