package com.wz.thread.enums;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* 使用枚举实现单例模式
* @author Administrator
*
*/
public class MyObject {
public enum MyEnumSingletion{
connectionFactory;
private Connection connection;
private MyEnumSingletion() {
try {
System.out.println("创建MyObject对象:");
String url = "jdbc:sqlserver://localhost:1433;databaseName=MyNet";
String username = "sa";
String password = "nrblwbb7";
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
Class.forName(driverName);
connection = DriverManager.getConnection(url,username,password);
} catch (Exception e) {
e.printStackTrace();
}
}
public Connection getConnection() {
return connection;
}
}
public static Connection getConnection() {
return MyEnumSingletion.connectionFactory.getConnection();
}
}
package com.wz.thread.enums;
public class MyThread extends Thread {
@Override
public void run() {
super.run();
for (int i = 0; i < 5; i++) {
System.out.println(MyObject.getConnection().hashCode());
}
}
}
package com.wz.thread.enums;
/**
* 输出的hascode值相同,说明是同一个对象
* @author Administrator
*
*/
public class Run {
public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();
t1.start();
t2.start();
t3.start();
}
}