简体   繁体   English

对同步和线程安全感到困惑吗? 爪哇

[英]Confused about synchronization and thread safe ? java

Actually, I am a bit confused in regards of several explanation from website or blog about synchronization and thread-safe. 实际上,对于网站或博客中有关同步和线程安全的几种解释,我有些困惑。 I've done some research on different class of Core Java Api or Java Framework (Collections). 我对Core Java Api或Java Framework(集合)的不同类进行了一些研究。 And i've often noticed that some class are synchronize and thread-safe which means, at a time, only one thread can access the code. 而且我经常注意到某些类是同步的并且是线程安全的,这意味着一次只能有一个线程可以访问代码。

But i need some precision : 但是我需要一些精度:

  • A class is synchronize so its thread-safe ? 一个类正在同步, 因此其线程安全吗?
  • Or synchronize and thread-safe have two different meaning ? 还是同步和线程安全有两个不同的含义?

Best regards 最好的祝福

A class is synchronize so its thread-safe ? 一个类正在同步,因此其线程安全吗?

A class is not synchronized. 类未同步。 Rather a method, or a block of code is synchronized. 而是方法或代码块是同步的。

Synchronization (using synchronized ) is one way to make code thread-safe. 同步(使用synchronized )是使代码线程安全的一种方法。 There are other ways. 还有其他方法。

Or synchronize and thread-safe have two different meaning ? 还是同步和线程安全有两个不同的含义?

Yes. 是。 They have different meanings. 它们具有不同的含义。


And i've often noticed that some class are synchronize and thread-safe which means, at a time, only one thread can access the code. 而且我经常注意到某些类是同步的并且是线程安全的,这意味着一次只能有一个线程可以访问代码。

Actually, if you "noticed" that, you were not paying attention! 实际上,如果您“注意到”该信息,则说明您没有注意!

With a synchronized method , only one thread can access the code while holding a given lock; 使用synchronized 方法时 ,只有一个线程可以在持有给定锁的同时访问代码。 ie you get mutual exclusion. 也就是说,您会互相排斥。 If two threads use different locks, then you won't get mutual exclusion. 如果两个线程使用不同的锁,那么您将不会相互排斥。

The other thing to note is that merely using synchronized does not guarantee thread-safety. 要注意的另一件事是仅使用synchronized并不能保证线程安全。 You need to use it in the right way: 您需要以正确的方式使用它:

  • threads need to synchronize on the appropriate objects / locks 线程需要在适当的对象/锁上进行同步
  • threads need to synchronize in all appropriate code 线程需要在所有适当的代码中进行同步
  • if the code entails acquiring multiple locks, the locks need to be acquired in an order that avoids deadlocks. 如果代码需要获取多个锁,则需要以避免死锁的顺序获取锁。

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

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