1 单例对象
/**
* @Title:SingleEntity
* @Author Tony
* @Date: 2014年6月20日 下午2:20:25
* @Description: 验证 单例对象的属性 在多线程中访问时不安全的
*/
public class SingleEntity {
private static SingleEntity singleEntity ;
private static String lock="" ; //锁对象不能为空
public static String temp;
//私有的构造函数
private SingleEntity(){
}
public static SingleEntity getSingleEntity(){
//System.out.println(temp+"========"+Thread.currentThread() );
try {
temp = Thread.currentThread().getName() ;//测试用
Thread.sleep(5000);
System.out.println( Thread.currentThread()+"======"+temp );//测试使用
if(singleEntity ==null){
synchronized (lock) { //同步锁为了保证对象的创建只有一个
if(singleEntity ==null ){
System.out.println("33333======="+Thread.currentThread()+"=====创建单例对象");
singleEntity = new SingleEntity();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
return singleEntity;
}
}
2 线程测试类
/**
* @Title:TestThead
* @Author Tony
* @Date: 2014年6月20日 下午2:23:10
* @Description: 线程类
*/
public class TestThead extends Thread {
public static void main(String[] args) {
TestThead t1 = new TestThead();
TestThead t2 = new TestThead();
TestThead t3 = new TestThead();
t1.start();
t2.start();
t3.start();
TestThead t ;
for(int i=0;i<50;i++ ){
t = new TestThead();
t.start();
}
}
@Override
public void run() {
SingleEntity singleEntity1 = SingleEntity.getSingleEntity();
//System.out.println( Thread.currentThread() +" "+singleEntity1 );
}
}