块级同步 [英] Block level synchronization
问题描述
传递给synchronized的参数有什么意义?
What is the significance of parameter passed to synchronized?
synchronized ( parameter )
{
}
实现块级同步.在某处我看到像
to achieve block level synchronization. Somewhere i saw code like
class test
{
public static final int lock =1;
...
synchronized(lock){
...
}
}
我不明白这段代码的目的.
I don't understand the purpose of this code.
谁能给我一个更好的例子和/或解释一下?
Can anyone give me a better example and/or explain it?
推荐答案
锁定参考.基本上两个线程不会同时执行使用相同引用同步的代码块.正如 Cletus 所说,同步 方法 大体上等同于在方法内部使用 synchronized (this)
.
It's the reference to lock on. Basically two threads won't execute blocks of code synchronized using the same reference at the same time. As Cletus says, a synchronized method is mostly equivalent to using synchronized (this)
inside the method.
我非常希望您看到的示例代码不是完全那样 - 您正在尝试对原始变量进行同步.同步仅适用于监视器(通过引用)——即使它 是合法的代码,x
也会被装箱,这会导致一些非常 奇怪的行为,因为一些整数总是被装箱到相同的引用,而其他的每次装箱时都会创建一个新对象.幸运的是,Java 编译器意识到这是一个非常糟糕的主意,并且会为您发布的代码提供编译时错误.
I very much hope that the example code you saw wasn't quite like that - you're trying to synchronize on a primitive variable. Synchronization only works on a monitor (via a reference) - even if it were legal code, x
would be boxed, which would lead to some very odd behaviour, as some integers will always be boxed to the same references, and others will create a new object each time you box. Fortunately, the Java compiler realises this is a very bad idea, and will give you a compile-time error for the code you've posted.
更合理的代码是:
class Test
{
private static final Object lock = new Object();
...
synchronized(lock){
...
}
}
我已将锁设为私有,并将其类型更改为 Object
.它是否应该是静态的取决于具体情况——如果您想从多个线程访问/更改静态数据,通常会使用静态变量;当您想要从多个线程访问/更改每个实例的数据时,实例变量通常用于锁定.
I've made the lock private, and changes its type to Object
. Whether or not it should be static depends on the situation - basically a static variable is usually used if you want to access/change static data from multiple threads; instance variables are usually used for locks when you want to access/change per-instance data from multiple threads.
这篇关于块级同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!