/**
* 饿汉模式与懒汉模式的使用实例
* 1.饿汉模式不存在线程安全问题,因为单例对象在对象创建时候,已经存在
* 2.懒汉模式存在线程安全问题,线程访问的时候可能创建多个单例对象
* 3.推荐用饿汉模式进行多线程的访问,不存在线程安全问题
*/
public class SingleThreadAccess {
public static void main(String[] args) {
AccessSingle single = new AccessSingle();
Thread t1 = new Thread(single);
Thread t2 = new Thread(single);
t1.start();
t2.start();
}
}
/**
* 定义饿汉单例模式
*/
class MyPerson{
int age = 34;
String name = "tom";
}
class Demo {
private static final MyPerson person = new MyPerson();
public static MyPerson getInstance(){
return person;
}
}
/**
* 定义懒汉单例模式
*/
class Demo2{
private static MyPerson person;
public static MyPerson getInstance(){
//加入if判断,如果单例对象已经存在,那么直接返回该对象,而不用进行锁定判断
if(person == null){
synchronized (Demo2.class) {
if(person==null){
person = new MyPerson();
}
}
}
return person;
}
}
class AccessSingle implements Runnable{
@Override
public void run() {
MyPerson person = Demo2.getInstance();//懒汉单例模式
MyPerson person2 = Demo.getInstance();//饿汉单例模式
System.out.println(Thread.currentThread().getName()+"======"+person);
System.out.println(Thread.currentThread().getName()+"======"+person2);
}
}
饿汉模式和懒汉模式的多线程访问问题
最新推荐文章于 2024-02-05 12:35:28 发布