Open TinaYu1 opened 5 years ago
private static SingletonTest SerializePerson() throws FileNotFoundException,
IOException {
SingletonTest testSingleTon = SingletonTest.getInstance();
try(ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream(
new File("F:/SingletonTest.txt")))) {
oo.writeObject(testSingleTon);
System.out.println(testSingleTon);
oo.close();
}
return testSingleTon;
}
/**
* MethodName: DeserializePerson
* Description:
* @author xudp
* @return
* @throws Exception
* @throws IOException
*/
private static SingletonTest DeserializePerson() throws Exception, IOException {
SingletonTest testSingleTon = null;
try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
new File("F:/SingletonTest.txt")))) {
testSingleTon = (SingletonTest) ois.readObject();
}
return testSingleTon;
}
private static void singletonTest() {
Runnable createSingletonClass = () -> {
try {
Class singletonTestClass = Class.forName("SingletonTest");
Constructor[] cts = singletonTestClass.getDeclaredConstructors();
System.out.println("size: " + cts.length);
cts[0].setAccessible(true); //访问权限打开setAccessible(true),就可以访问私有构造函数
SingletonTest singletonTestClas = (SingletonTest)cts[0].newInstance();
System.out.println(singletonTestClas);
} catch (Exception e) {
e.printStackTrace();
}
};
Runnable createSingletonDeserialize = () -> {
try {
SingletonTest singletonTestDeserialize = DeserializePerson();
System.out.println(singletonTestDeserialize);
} catch (Exception e) {
e.printStackTrace();
}
};
Runnable createSingletonCommon = () -> {
try {
SingletonTest singletonTest = SingletonTest.getInstance();
System.out.println(singletonTest);
} catch (Exception e) {
e.printStackTrace();
}
};
for (int i = 0; i < 30; i++) {
Thread thread = new Thread(createSingletonClass);
thread.start();
}
}
import java.io.Serializable; import java.util.Date;
/**
Created by Tina.Yu on 2018/11/30. */ public class SingletonTest implements Serializable { private static SingletonTest ourInstance = new SingletonTest();
public static SingletonTest getInstance() { return ourInstance; }
private SingletonTest() { if (ourInstance != null) { throw new RuntimeException("Create singleton more than once"); } }
private Object readResolve() { return getInstance(); } }