我想制作一个单例类Phone,这样它就可以初始化(用数字)并且并发安全。所以,这就是我带来的:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class PhoneTest {
public static void main(String... args){
System.out.println(Phone.getInstance().getNumber());
}
static final class Phone {
private final String number;
private final static Phone instance;
static {
instance = new Phone(PhonePropertyReader.readPhoneNumber());
}
private Phone(String number) {
this.number = number;
}
public static Phone getInstance() {
if (instance == null) throw
new IllegalStateException("instance was not initialized");
return instance;
}
public String getNumber() {
return number;
}
}
static final class PhonePropertyReader {
static String readPhoneNumber() {
File file = new File("phone.properties");
String phone = "";
System.out.println(file.getAbsolutePath());
if (!file.exists()) {
return phone = "555-0-101";
}
try {
BufferedReader r = new BufferedReader(new FileReader(file));
phone = r.readLine().split("=")[1].trim();
r.close();
} catch (IOException e) {
}
return phone;
}
}
}
我还有一个文件phone.properties,其中包含
phone=12345
这是一个好的解决方案吗?并发安全吗?
最佳答案
我相信Enum仍然是在 java 中实现线程安全单例的最佳方式。
关于java - java中带有初始化参数的并发安全单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16001933/