使用枚举数据类型实现单例模式

如:
public enum  MyObject {
connectionFactory;
private Connection connection;
private MyObject(){
try {
System.out.println("调用了MyObject的构造");
String url="jdbc:oracle:thin:@118.192.22.167:1521/lbdtest01";
String username="lbdtest01";
String pwd="lbd%^test01";
String driverName="oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
connection= DriverManager.getConnection(url,username,pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection getConnection(){
return connection;
}
}
class MyThread extends Thread{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(MyObject.connectionFactory.getConnection().hashCode());
}
}
}
class MyRun{
public static void main(String[] args) {
MyThread t1=new MyThread();
MyThread t2=new MyThread();
MyThread t3=new MyThread();
t1.start();
t2.start();
t3.start();
}
}
原文地址:https://www.cnblogs.com/345214483-qq/p/6472162.html