java 同步与信号量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16907992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Synchronized Vs Semaphore
提问by Addict
While reading concurrency in Java, I have following doubts:
在阅读 Java 并发时,我有以下疑问:
Does Java provides lower level construct then synchronized for synchronization?
In what circumstances will we use semaphore over synchronized (which provides monitor behaviour in Java)
Java 是否提供较低级别的构造然后同步以进行同步?
在什么情况下我们会使用信号量而不是同步(它在 Java 中提供监视器行为)
回答by Marichyasana
Synchronized allows only onethread of execution to access the resource at the same time. Semaphore allows up to n(you get to choose n) threads of execution to access the resource at the same time.
同步只允许一个执行线程同时访问资源。信号量允许最多n 个(您可以选择 n 个)执行线程同时访问资源。
回答by Evgeniy Dorofeev
There is also
volatile
keyword, according to http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.htmlvolatile
variable access is more efficient than accessing these variables through synchronized codejava.util.concurrent.Semaphore
is used to restrict the number of threads that can access a resource. That is, whilesynchronized
allows only one thread to aquire lock and execute the synchonized block / method, Semaphore gives permission up to n threads to go and blocks the others.
还有
volatile
关键字,根据http://docs.oracle.com/javase/tutorial/essential/concurrency/atomic.htmlvolatile
变量访问比通过同步代码访问这些变量效率更高java.util.concurrent.Semaphore
用于限制可以访问资源的线程数。也就是说,虽然synchronized
只允许一个线程获取锁并执行同步块/方法,但信号量允许最多 n 个线程去并阻止其他线程。
回答by RalphChapin
There is also atomics. This gives access to the basic hardware compare-and-swap command that's the basis of all synchronization. It allows you, for example, to increment a number safely. If you ++
a volatile field, another thread executing the same instruction could read the field before your thread writes to it, then write back to it afteryour thread. So one increment gets lost. Atomics do the read and write "atomically" and so avoid the problem.
还有原子。这样就可以访问作为所有同步基础的基本硬件比较和交换命令。例如,它允许您安全地递增一个数字。如果您++
是 volatile 字段,则执行相同指令的另一个线程可以在您的线程写入该字段之前读取该字段,然后在您的线程之后写回该字段。所以一个增量丢失了。Atomics 以“原子方式”进行读写,因此避免了这个问题。
Actually, volatiles, synchronized statements, andatomics tend to force all thread data to be refreshed from main memory and/or written to main memory as appropriate, so none of them are reallythat low level. (I'm simplifying here. Unlike C#, Java does not really have a concept of "main memory".)
实际上,volatiles、synchronized statements和atomic 往往会强制所有线程数据从主内存刷新和/或适当写入主内存,因此它们都不是那么低的级别。(我在这里进行了简化。与 C# 不同,Java 并没有真正的“主内存”概念。)