我需要将连接池对象传递给ScheduledExecutorService线程,但我遇到了困难。我试图在声明前面添加final但是会抛出以下错误...无法分配最终的局部变量连接。它必须为空白且不使用复合赋值
如何正确传递此连接对象?
public class AdminManager extends JFrame {
private JPanel contentPane;
private JTable tableQueue;
private JTable tableFilled;
/**
* Launch the application.
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
AdminManager frame = new AdminManager();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
BoneCP connectionPool = null;
Connection connection = null;
try {
// load the database driver (make sure this is in your classpath!)
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
return;
}
try {
// setup the connection pool
BoneCPConfig config = new BoneCPConfig();
config.setJdbcUrl("jdbc:mysql://192.0.0.1:3306/db"); // jdbc url specific to your database, eg jdbc:mysql://127.0.0.1/yourdb
config.setUsername("root");
config.setPassword("");
connectionPool = new BoneCP(config); // setup the connection pool
connection = connectionPool.getConnection(); // fetch a connection
if (connection != null){
System.out.println("Connection successful!");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable(){
@Override
public void run(){
System.out.println("Working ... ");
String sql = "SELECT * FROM table;";
Statement st;
try {
st = connection.createStatement();
ResultSet rs = st.executeQuery(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 2000, 1000, TimeUnit.MILLISECONDS);
答案 0 :(得分:1)
您可以定义仅在执行程序中使用的虚拟引用:
final Connection conn = connection;
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new Runnable(){
@Override
public void run(){
System.out.println("Working ... ");
String sql = "SELECT * FROM table;";
Statement st;
try {
st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, 2000, 1000, TimeUnit.MILLISECONDS);
如果问题无法以这种方式解决(无法查看其余代码),您可以定义一个外部任务类来保存代码:
class ThreadTask implements Runnable {
private Connection connection;
public ThreadTask(Connection c) {
connection = c;
}
@Override
public void run() {
System.out.println("Working ... ");
String sql = "SELECT * FROM table;";
Statement st;
try {
st = connection.createStatement();
ResultSet rs = st.executeQuery(sql);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
和
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.scheduleAtFixedRate(new ThreadTask(connection));