回答

收藏

JDBC和多线程

技术问答 技术问答 507 人阅读 | 0 人回复 | 2023-09-14

我正在尝试使用多线程方法运行一些查询,但是我认为我做错了,因为我的程序大约需要五分钟才能运行一个简单的select语句,例如; L. m& O; {$ ^4 K; H8 J2 U
SELECT * FROM TABLE WHERE ID = 123'* G$ S- |7 Z4 t1 E0 Z9 M
我的实现如下,并且我正在使用一个连接对象。8 r8 _1 e( T- D: A6 u
在我的运行方法中9 s; C- ^( j3 Q6 F
public void run() {
, D4 T7 I" D' R% u5 @/ Y7 }( C    runQuery(conn, query);
5 V: N. `( F. C; K0 a! _) P}
9 I: N7 A6 Z, p" q; ^5 v% ~runQuery方法
3 x5 X0 @1 v7 U$ p& dpublic void runQuery(Connection conn, String queryString){
( ?9 B) H6 L4 f. V# u! U: d, V    Statement statement;
% t5 O6 w0 ?, t    try {
& r- |, v1 r$ {7 i          statement = conn.createStatement();
3 H% k4 T9 u; y& Z, _4 c+ H3 u( m" ^. o          ResultSet rs = statement.executeQuery(queryString);$ ]0 z9 v$ C- x; T4 A* |6 b
          while (rs.next()) {}+ n) L, j- g' b; ~- l
    } catch (SQLException e) {; u' F) V# s$ z. t/ H1 u
        e.printStackTrace();$ ?$ I1 t3 Q4 H) H( ]2 x7 v0 \
    }
( T" A* k- R% ]. [4 G}! R% u, L3 K5 p( \) I
最后,在main方法中,我使用下面的代码片段启动线程。
9 H8 V* m* i9 s; U# |8 yMyThread bmthread = new MyThread(conn, query);9 |+ N. K* ^( n- B. U/ V
ArrayList allThreads = new ArrayList();
3 e- z- `1 u: q! F2 G( Pdouble start = System.currentTimeMillis();; e+ {: S) L4 K1 f+ o1 k  a
    int numberOfThreads = 1;
4 W: V/ _! e7 @- e  K    for(int i=0; i更新:我现在为每个线程使用单独的连接。- A8 B" t* f8 r8 K
ArrayList sqlConn = new ArrayList();
/ r( d+ F$ G6 g& J9 S+ J    for(int i =0; i如rohivats和Asaph所说,一个连接必须由一个线程使用,并且只有一个线程,即考虑使用数据库连接池。考虑到c3p0,DBCP和类似的东西几乎被遗弃了,我将使用HikariCP,它确实是快速而可靠的。
3 u8 j2 J# T7 O9 |如果您想要非常简单的内容,则可以使用线程安全集合(例如LinkedList)来实现一个非常简单的连接池,例如:% `+ M" D- P0 ^/ r- c4 Y2 @2 G7 [  L% Z5 \
public class CutrePool{
/ u4 B" V6 ?$ q2 M1 m4 G$ t      String connString;    $ y  I0 l( _8 a
      String user;
" K$ a2 W( D9 m, \# T$ U      String pwd;; f2 P! t3 M9 k2 e+ ]6 t+ N/ @
      static final int INITIAL_CAPACITY = 50;, g; R- l8 q( B' H- M  I+ i0 R6 h
      LinkedList pool = new LinkedList();
2 P) G: F  t* Y0 Y- S- f      public String getConnString() {  J; ]/ ]0 Y% [6 {
          return connString;
! g0 H7 j; m  x- I/ i      }4 _6 k$ y* I. p4 Z# N. }
      public String getPwd() {
+ \/ T( T5 p4 d% K+ x& f. |" ]          return pwd;
. I$ ]( j% M: _0 w/ u# ]9 C      }
! a$ F- V# Z( Z: I  ^/ w- h0 I      public String getUser() {2 e, {7 Z( q; C: L) z" N. l$ E
          return user;
$ o/ `8 ^' c' d0 _0 M      }1 k, s/ d3 z  O1 w- ?' o& b- N
      public CutrePool(String connString, String user, String pwd) throws SQLException {0 ?0 H! g% _& ^  F, {+ p
          this.connString = connString;
+ n. R0 f/ T3 M' r5 b          for (int i = 0; i 如您所见,getConnection和returnConnection方法被同步为线程安全的。获得连接(conn =
. O% {+ V6 Z; ipool.getConnection();),不要忘了在使用后返回/释放连接(pool.returnConnection(conn);)
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则