Threads access on Synchronized Block/Code Java(同步块/代码 Java 上的线程访问)
问题描述
我正在阅读 Synchronized 工作.示例如下:
I was reading Synchronized working. Here is the example:
public class Singleton{
private static volatile Singleton _instance;
public static Singleton getInstance(){
if(_instance == null){
synchronized(Singleton.class){
if(_instance == null)
_instance = new Singleton();
}
}
return _instance;
}
假设两个线程 A 和 B 正在访问 getInstance(); 方法,如果线程 A 在 synchronized 块中,则线程 B 将跳过该块并执行下一个块/语句,或者将等待/阻塞直到线程 A 离开 synchronized 块.
Let Suppose two Thread A and B are accessing getInstance(); method,
If thread A is in synchronized block then thread B will skip that block and execute next block/statement or will wait/blocked until Thread A leave the synchronized block.
2nd是什么,为什么Singleton.class在synchronized参数中,什么时候可能是null
2nd What is, why is Singleton.class in synchronized parameter and when it could be null
下面的语句是真的吗?
对象上有内在锁:
class A
{
public synchronized void method1(){...}
public synchronized void method2(){...}
}
如果线程 A 在 method1 中,则 threadB 无法进入 method2 或任何其他同步方法.
If thread A is in method1 then threadB cannot enter method2 or any other synchronized method .
推荐答案
1:线程B会一直等待,直到线程A释放同步对象上的锁并执行代码,才获取同步对象上的锁.
1: Thread B will wait, until Thread A will release the lock on the synchronized object and execute the code, after it will aquire the lock on the synchronized object.
2:Singleton.class 是代表该类的对象.您正在对其进行同步,因为您的 _instance-object 为空.
2: Singleton.class is the object, that represent that class. You are synchronizing on it, since your _instance-object is null.
public synchronized void method1(){...}
在对象上同步,你调用那个方法,这意味着,如果你这样调用,2个线程将互相等待:
is synchronizing on the Object, on that you call that method, that means, 2 Threads will wait for each other, if you call it like this:
final A a = new A();
new Thread(new Runnable(){
public void run(){
a.method1();
}
}).start();
a.method1();
但如果你在不同的对象上调用它,两个线程将并行执行:
but both threads will be executed parallel, if you call it on different Objects:
A a = new A();
final A b = new A();
new Thread(new Runnable(){
public void run(){
b.method1();
}
}).start();
a.method1();
最后一个问题:对了,线程B不会进入方法2,因为同步方法锁定了对象
last question: right, Thread B will not enter method 2, since the synchronized method locks on the Object
顺便说一句.
public synchronized void method1(){...}
相当于:
public void method1(){
synchronized(this){
...
}
}
这篇关于同步块/代码 Java 上的线程访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:同步块/代码 Java 上的线程访问
- Eclipse 的最佳 XML 编辑器 2022-01-01
- 如何指定 CORS 的响应标头? 2022-01-01
- java.lang.IllegalStateException:Bean 名称“类别"的 BindingResult 和普通目标对象都不能用作请求属性 2022-01-01
- 获取数字的最后一位 2022-01-01
- 在 Java 中,如何将 String 转换为 char 或将 char 转换 2022-01-01
- GC_FOR_ALLOC 是否更“严重"?在调查内存使用情况时? 2022-01-01
- 如何使 JFrame 背景和 JPanel 透明且仅显示图像 2022-01-01
- 转换 ldap 日期 2022-01-01
- 将 Java Swing 桌面应用程序国际化的最佳实践是什么? 2022-01-01
- 未找到/usr/local/lib 中的库 2022-01-01
