guguoyi / shareber

7 stars 0 forks source link

2018-12-07[Tina Yu] Singleton #3

Open TinaYu1 opened 5 years ago

TinaYu1 commented 5 years ago

import java.io.Serializable; import java.util.Date;

/**

HijikataToushirou commented 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();
    }
}