java里数据能否做单例_java 单例测试中的不能将所有的数据加入单例类中?

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来保证数据吧?

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值