本文介绍Java单例模式第四种
这种策略的模式是使用Java的关键字synchronized修饰了getInstance()方法,用的是同步方法。这在操作系统中被认为是管程。管程的实质不是由操作系统进行了特殊操作,而是由编译器进行了同步代码块的封装,类似于C语言中的pthread_mutex_lock和pthread_mutex_unlock,而在操作系统层面,实际上就是一对原子操作,也被成为原语,意思就是对于共享资源的加锁。只有使用完了这个资源才会释放这个资源,由其他进程使用。
synchronized 修饰的方法或者代码块。此处是加了全局锁,其实锁定的是Student04.class ,每次执行getInstance方法都要判断是否获取到了锁对象, 因此是可以保证获取的实例是同一个,但是其他线程在运行到这个方法的时候,因为获取不到锁对象,因此会不断的尝试去获取锁对象,直到获取到为止,因此会有效率上面的影响。
代码部分
package singleton;
public class Student04 {
public static Student04 instance;
private Student04(){
}
public synchronized static Student04 getInstance() {
if (instance == null) {
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
instance = new Student04();
}
return instance;
}
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Student04.getInstance().hashCode());
}
}).start();
}
}
}
运行代码输出:
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163
4661163