package threadandsingleton;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Created by hadoop on 17-3-13.
*/
public class Singleton {
//懒汉模式。。。。。
private static Singleton singleton;
private List map;
private Singleton(){
map=new LinkedList<>();
}
private static class MySingletonHandler{
private static Singleton instance = new Singleton();
}
public static Singleton getSingleton(){
/*if(singleton==null){
try {
Thread.currentThread().sleep(300L);
} catch (InterruptedException e) {
e.printStackTrace();
}
singleton=new Singleton();
}
return singleton;*/
try {
Thread.currentThread().sleep(3000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
return MySingletonHandler.instance;
}
public Boolean add(Integer integer){
return map.add(integer);
}
public List getList(){
return map;
}
}
package threadandsingleton;
import java.util.LinkedList;
import java.util.List;
/**
* Created by hadoop on 17-3-13.
*/
public class ThreadTeset extends Thread {
Integer integer;
public ThreadTeset(Integer integer) {
this.integer = integer;
}
public void run(){
//我猜有一部分拿到了没有实例化的单例类
System.out.println(Thread.currentThread().getName()+integer);
Singleton singleton=Singleton.getSingleton();
if(singleton==null){
System.out.println("catch a singleton named null");
}
if(!singleton.add(integer)){
System.out.println("there is an example wrong");
}
System.out.println(singleton.getList().size());
}
//多线程访问单例模式居然会出现空指针异常。。。。
public static void main(String[] args) {
List threadTesets=new LinkedList<>();
for (int i = 0; i < 2000; i++) {
threadTesets.add(new ThreadTeset(i));
}
for (ThreadTeset t:
threadTesets) {
t.start();
/*try {
t.join();
} catch (InterruptedException e) {
e.printStackTrace();
}*/
}
try {
Thread.currentThread().sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Singleton.getSingleton().getList().size());;
//System.out.println(Singleton.getSingleton().getList());
}
}
结果中
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1989
只有1989个数据被加入到封装的集合类中了原因是什么
这可能是由于HashSet的线程不安全导致的,在多线程中我们应该使用cocurrentMap来保证数据吧?