——–昨天听到一句话,人不要常立志,要立长志
嗯,设计模式最简单的就是单例模式了吧,慢慢学,把学到的东西记录下来吧.单例还是挺常见的,也是很好理解的,来看看常见实现
一般实现
package com.notes.single;
public class Director {
private static Director director = null; //导演只有一个
private Director(){ //让类不能外部new
}
public static Director getInstance(){
if(director == null){
director = new Director();
System.out.println("=================new le");
}
return director;
}
}
但这样是有问题的,我们来看看
package com.notes.single;
public class SingleTest {
public static void main(String[] args) {
new Thread(new MyTask()).start();
new Thread(new MyTask()).start();
new Thread(new MyTask()).start();
new Thread(new MyTask()).start();
new Thread(new MyTask()).start();
new Thread(new MyTask()).start();
}
}
class MyTask implements Runnable{
public void run() {
// TODO Auto-generated method stub
Director.getInstance();
}
}
输出
=================new le
=================new le
=================new le
即多线程情况下有问题,所以我们改造下
public static Director getInstance(){
if(director == null){
synchronized (Director.class) {
if(director == null){
director = new Director();
System.out.println("=================new le");
}
}
}
return director;
}
嗯,这样就不会出现问题了.