java synchronized 效率_对于Java多线程synchronized(.class)和valatile的困惑?

这是head first 设计模式中单例模式第182页的一段代码

public class Singleton {

// 为什么要使用volatile关键字?

private volatile static Singleton uniqueInstance;

private Singleton() {}

public static Singleton getInstance() {

if (uniqueInstance == null) {

/* 为什么要使用synchronized (Singleton.class),使用synchronized(this)或者

synchronized(uniqueInstance)不行吗?而且synchronized(uniqueInstance)的效率更加高?*/

synchronized (Singleton.class) {

if (uniqueInstance == null) {

uniqueInstance = new Singleton();

}

}

}

return uniqueInstance;

}

}

问题一:为什么要使用volatierle关键字?

问题二:为什么要使用synchronized (Singleton.class),使用synchronized(this),或者synchronized(uniqueInstance)不行吗?而且synchronized(uniqueInstance)的效率更加高?

Stackoverflow上面的答案

public class Foo extends Thread {

private volatile boolean close = false;

public void run() {

while(!close) {

// do work

}

}

public void close() {

close = true;

// interrupt here if needed

}

}

you need volatile because the thread reading close in the while loop is different from the one that calls close(). Without volatile, the thread running the loop may never see the change to close.

static void myMethod() {

synchronized(MyClass.class) {

//code

}

}

is equivalent to

static synchronized void myMethod() {

//code

}

and

void myMethod() {

synchronized(this) {

//code

}

}

is equivalent to

synchronized void myMethod() {

//code

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值