1.Properties类
1.1包
java.util.Properties
1.2类结构
public class Properties extends Hashtable<Object,Object>
1.3配置文件
resources/user.properties
user.username = admin
user.password = 223
1.4解析
Properties prop = new Properties();
String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
String fileName = path+"com/dyit/resources/user.properties";
prop.load(new FileReader(fileName));
System.out.println("用户名: " + prop.getProperty("user.username"));
System.out.println("密码: " + prop.getProperty("user.password"));
2.设计模式-单例模型
2.1 什么是单例?
创建型模式: 创建对象·
核心: 内存中只有唯一的一个对象
2.2 懒汉模式的线程安全问题
Executor pool = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
pool.execute(() -> {
for (int j = 0; j < 10; j++) {
System.out.println(Thread.currentThread().getName() + ": " + Singleton.getIntance().hashCode());
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
pool-1-thread-6: 1335324870
pool-1-thread-10: 1335324870
pool-1-thread-1: 1967528551
pool-1-thread-8: 1335324870
pool-1-thread-4: 2087870959
pool-1-thread-9: 1335324870
pool-1-thread-7: 1335324870
2.3 线程安全解决方案
ReentrantLock/synchronized
package com.dyit.singleton;
import java.util.concurrent.locks.ReentrantLock;
import javax.xml.crypto.dsig.keyinfo.RetrievalMethod;
public class Singleton {
private static Singleton instance = null;
private final static ReentrantLock lock = new ReentrantLock();
private Singleton() {
}
public static Singleton getIntance() {
lock.lock();
try {
if (instance == null) {
instance = new Singleton();
}
} finally {
lock.unlock();
}
return instance;
}
}
2.4 饿汉模式
package com.dyit.singleton;
public class Singleton2 {
private final static Singleton2 instance
= new Singleton2();
private Singleton2() {}
public static Singleton2 getIntance() {
return instance;
}
}
|