0

我需要将连接池对象传递给 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);
4

1 回答 1

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));
于 2012-07-08T17:47:30.143 回答