同步和静态同步有什么区别? [英] What is the difference between synchronized and static synchronized?
问题描述
对于旅行预订网络应用程序,其中有100个并发用户登录,
应该预订机票并生成电子机票号码是通过同步还是静态同步方法实现的?
For a travel booking web application, where there are 100 concurrent users logged in, should ticket booking and generating an "E-Ticket Number" be implemented by a "synchronized" or a "static synchronized" method?
推荐答案
那么,您是否了解静态方法和实例方法之间的区别?
Well, are you aware of the difference between a static method and an instance method in general?
synchronized
的唯一区别在于,在VM开始运行该方法之前,它必须获取监视器。对于实例方法,获取的锁是与您调用方法的对象关联的锁。对于静态方法,获取的锁与类型本身相关联 - 因此没有其他线程可以同时调用任何其他同步的静态方法。
The only difference that synchronized
makes is that before the VM starts running that method, it has to acquire a monitor. For an instance method, the lock acquired is the one associated with the object you're calling the method on. For a static method, the lock acquired is associated with the type itself - so no other threads will be able to call any other synchronized static methods at the same time.
In换句话说,这个:
In other words, this:
class Test
{
static synchronized void Foo() { ... }
synchronized void Bar() { ... }
}
大致相当于:
class Test
{
static void Foo()
{
synchronized(Test.class)
{
...
}
}
void Bar()
{
synchronized(this)
{
...
}
}
}
通常我根本不会使用同步方法 - 我更喜欢在私有锁引用上显式同步:
Generally I tend not to use synchronized methods at all - I prefer to explicitly synchronize on a private lock reference:
private final Object lock = new Object();
...
void Bar()
{
synchronized(lock)
{
...
}
}
您还没有提供足够的信息来确定您的方法应该是静态或实例方法,或者它是否应该同步。多线程是一个复杂的问题 - 我强烈建议你阅读它(通过书籍,教程等)。
You haven't provided nearly enough information to determine whether your method should be a static or instance method, or whether it should be synchronized at all. Multithreading is a complex issue - I strongly suggest that you read up on it (through books, tutorials etc).
这篇关于同步和静态同步有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!