我的线程程序不起作用,因为我希望它起作用。首先是我的主类,从那里开始我的线程:import static java.lang.Thread.currentThread;public class Main {public static void main(String[] args) throws IOException, NamingException, ClassNotFoundException { Properties property = new Properties(); property.load(new FileReader(new File(args[0]))); DataSource ds = DataSource.newInstance(property); Class.forName("org.postgresql.Driver"); ConnectionPool connectionPool = new ConnectionPool(); System.out.println(currentThread().getName()); ConnectionPoolManager manager = new ConnectionPoolManager(connectionPool, ds); manager.start(); }}这是我的 ConnectionPool 类package com.telbook.connectionPooling;import java.sql.Connection;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;public class ConnectionPool {private List<PoolObject> poolObjects = new ArrayList<>();public List<PoolObject> getPoolObjects() { return poolObjects;}public void setPoolObjects(List<PoolObject> poolObjects) { this.poolObjects = poolObjects;}public void put(Connection connection) { PoolObject poolObject = new PoolObject(); poolObject.setConnection(connection); poolObjects.add(poolObject);}public Connection getConnection() throws SQLException { for (PoolObject object: poolObjects) { if (!object.getInUse() && object.getConnection()!=null) { if (!object.getConnection().isClosed()) { if (object.getConnection().isValid(50)) { object.setInUse(true); return object.getConnection(); } } } } return null;}}
1 回答
aluckdog
TA贡献1847条经验 获得超7个赞
ArrayList
不是线程安全的,调度线程池中的线程可能无法获取最新元素,请尝试使用线程安全版本List
:
private List<PoolObject> poolObjects = Collections.synchronizedList(new ArrayList<PoolObject>());
添加回答
举报
0/150
提交
取消