s = null;
private ReentrantLock lock;
public DestGetConn2(ComboPooledDataSource source, ReentrantLock lock) {
this.postgres = source;
this.lock = lock;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(1000);
lock.lock();
postgres.getConnection();
lock.unlock();
System.out.println("I get a Connection! I am in " + Thread.currentThread().getName());
} catch (InterruptedException | SQLException e) {
e.printStackTrace();
}
}
}
}
5.最后总结一个效率还可以的工具类
package com.highgo.hgdbadmin.myutil;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0Util {
public static String SOURCE = "source";
public static String POSTGRES = "postgres";
private ComboPooledDataSource source = null;
private ComboPooledDataSource postgres = null;
private static C3P0Util instance = null;
private C3P0Util() {
source = new ComboPooledDataSource("source");
postgres = new ComboPooledDataSource("postgres");
}
public static final synchronized C3P0Util getInstance() {
if (instance == null) {
instance = new C3P0Util();
}
return instance;
}
public synchronized Connection getConnection(String dataSource) throws SQLException {
if ("source".equals(dataSource)) {
return source.getConnection();
} else if ("postgres".equals(dataSource)) {
return postgres.getConnection();
}
return null;
}
public synchronized void close(Connection conn) {
try {
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
}
}
public synchronized void close(Statement stat) {
try {
if (stat != null) {
stat.close();
stat = null;
}
} catch (SQLException e) {
}
}
public synchronized void close(ResultSet rest) {
try {
if (rest != null) {
rest.close();
rest = null;
}
} catch (SQLException e) {
}
}
public static void main(String[] args) {
new Thread(new TestThread(), "test").start();
}
private static class TestThread implements Runnable {
private String dataSource = "source";
@Override
public void run() {
while (true) {
try {
Connection conn = C3P0Util.getInstance().getConnection("");
System.out.println("hello,this is " + dataSource);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if ("source".equals(dataSource)) {
dataSource = "postgres";
} else {
dataSource = "source";
}
}
}
}
}