设为首页 加入收藏

TOP

ThreadLocal,LinkedBlockingQueue,线程池 获取数据库连接2改进(二)
2015-07-20 17:57:29 来源: 作者: 【 】 浏览:4
Tags:ThreadLocal LinkedBlockingQueue 线程 获取 数据库 连接 改进
e) { log.WriteLine("getConnection", e.getMessage()); } } } GetConnectionClazz jj = new GetConnectionClazz(); jj.start(); try { jj.join(); } catch (InterruptedException e) { log.WriteLine("getConnection()", e.getMessage()); } log.WriteLine("getConnection()","\u3010" + jj.getQueueSize() + "\u3011"+ "getConnecion\u6210\u529F\uFF1A" + jj.getConn()); return jj.getConn(); } } // class GG extends Thread { // public void run() { // for (;;){ // try { // ThreadLocalBlockingQueueUtils.getConnection(); // Thread.sleep(300); // } catch (Exception e) { // } // } // } // } /** * @descritpion 创建 数据库连接的线程类 * @author Administrator * */ class CreateConnection extends Thread { LinkedBlockingQueue queue = ThreadLocalBlockingQueueUtils .getQueue(); LogUtil log = new LogUtil(); public synchronized void run() { boolean result = false; while (true) { try { Random rand=new Random(); int num=ThreadLocalBlockingQueueUtils.getThreadPoolMaxNum()-ThreadLocalBlockingQueueUtils.getThreadPoolMinNum(); int randSize=rand.nextInt(num)+1; if(queue.size()>=randSize){ Thread.sleep(100); continue; } Connection conn = null; conn = DriverManager.getConnection( ThreadLocalBlockingQueueUtils.getUrl(), ThreadLocalBlockingQueueUtils.getUsername(), ThreadLocalBlockingQueueUtils.getPassword()); if (conn != null) { result = queue.offer(conn, 1, TimeUnit.SECONDS); } else { // System.out.println("DriverManager.getConnection is null"); log.WriteLine("CreateConnection.run()", "DriverManager.getConnection()返回 null"); continue; } if (result == false) { Thread.sleep(100); log.WriteLine("CreateConnection.run()", "已达到最大连接数queue.size()=" + queue.size()); // System.out.println("已经满了size=【" + queue.size() + "】"); } else { log.WriteLine("CreateConnection.run()", "\u3010" + queue.size() + "\u3011" + "createConnection success:" + conn); // System.out.println("\u3010" + queue.size() + "\u3011" // + "createConnection success:" + conn); } } catch (InterruptedException e) { // e.printStackTrace(); log.WriteLine("getConnection", e.getMessage()); // System.err.println(e.getMessage()); } catch (SQLException e) { log.WriteLine("getConnection", e.getMessage()); // e.printStackTrace(); // System.err.println(e.getMessage()); } } } }
首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇UVA - 590Always on the run(递.. 下一篇HDU 1863 畅通工程 (最小生成树)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: