赞
踩
private Singleton(String name) {
this.name = name;
}
public static Singleton getInstance() {
if (null == INSTANCE) {
synchronized (Singleton.class) {
if (null == INSTANCE) {
// 可能会出现指令重排序,即未进行成员变量name的初始化就退出了,
// 这样别人就会拿到未初始化(name=null)的Singleton对象
INSTANCE = new Singleton(“hh”);
}
}
}
return INSTANCE;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.nobody.thread;
import java.util.ArrayList;
import java.util.List;
/**
volatile不保证原子性,最终结果一般小于10000
若要保证原子性,直接将doCount方法加synchronized关键字即可,而volatile可有可无
@author Μr.ηobοdy
@date 2020-04-19
*/
public class VolatileDemo1 {
private volatile static int count = 0;
private /synchronized/ void doCount() {
for (int i = 0; i < 1000; i++) {
count++;
}
}
public static void main(String[] args) {
VolatileDemo1 v = new VolatileDemo1();
// 启动10个线程
List threads = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
threads.add(new Thread(v::doCount, “
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。