/**
* 线程安全的
*/
public class Example1 {
private Example1(){}
private static Example1 example1 = new Example1();
public static Example1 getInstance() {
return example1;
}
}
import lombok.extern.slf4j.Slf4j;
/**
* 线程不安全安全的
* <p>
* 线程A 执行到 example = new Example2();还未执行完,
* 线程B执行要进行 if (example == null)判断,最后可能创建多个实例
*/
@Slf4j
public class Example2 {
private Example2() {
}
private static Example2 example;
public static Example2 getInstance() {
if (example == null) {
example = new Example2();
}
return example;
}
}
import lombok.extern.slf4j.Slf4j;
/**
* 线程不安全安全的,性能低
* 每次获取实例都要获取锁性能比较低,
* 线程A创建了实例,但未写入到主内存中,这时候线程B读到的值便是null
*/
@Slf4j
public class Example3 {
private Example3() {
}
private static Example3 example;
public static synchronized Example3 getInstance() {
if (example == null) {
example = new Example3();
}
return example;
}
}
import lombok.extern.slf4j.Slf4j;
/**
* 线程不安全的,性能高
* * 在实例化的情况下不需要每次都获取锁,性能比较好,但是同样线程不安全的,
* * 线程A创建了实例,但未写入到主内存中,这时候线程B读到的值便是null
*/
@Slf4j
public class Example4 {
private Example4() {
}
private static Example4 example;
public static Example4 getInstance() {
if (example == null) {
synchronized (Example4.class) {
if (example == null) {
example = new Example4();
}
}
}
return example;
}
}
import lombok.extern.slf4j.Slf4j;
/**
* 线程安全的,性能高
* 在实例化的情况下不需要每次都获取锁,性能比较好,但是同样线程不安全的,
* 线程A创建了实例,由于变量使用volatile修饰,赋值后会立即写入到主内存,这时候线程B在读的时候也会从主内存中读取
*/
@Slf4j
public class Example5 {
private Example5() {
}
private volatile static Example5 example;
public static Example5 getInstance() {
if (example == null) {
synchronized (Example5.class) {
if (example == null) {
example = new Example5();
}
}
}
return example;
}
}
import lombok.extern.slf4j.Slf4j;
/**
* 使用枚举
*/
@Slf4j
public class Example6 {
private Example6() {
}
public final static Example6 getInstance() {
return Example6Enum.INSTANCE.getExample6();
}
enum Example6Enum {
INSTANCE(new Example6());
private Example6 example6;
Example6Enum(Example6 example6) {
this.example6 = example6;
}
public Example6 getExample6() {
return example6;
}
}
}
网友评论