并发编程-线程间的协作(四)

等待与通知模式实现一个简单的连接池,直接上代码


import java.util.LinkedList;

/**
 * 使用等待通知实现一个简单的数据库连接池
 * 
 * @author ckj
 *
 */
public class DbPool {
	/* 定义一个容器用做数据库连接池,由于数据库连接多做获取与释放操作所有选用LinkedList,池化技术与队列技术会在后续章节演示 */
	public LinkedList<Connection> connectionPool = new LinkedList<Connection>();


	
	public DbPool(int poolSize) {
		if (poolSize > 0) {
			for (int i = 0; i < poolSize; i++) {
				connectionPool.addLast( new Connection());
			}

		}
	}

	/* 归还连接,使用完连接后将连接重新放入池中 */
	/* 使用notifyAll 通知等待线程获取 */
	public void reConnection(Connection connection) {
		if (connection != null) {
			synchronized (connectionPool) {
				// 将连接放到最后
				connectionPool.addLast(connection);
				connectionPool.notifyAll();
			}
		}

	}

	/**
	 * 获取连接 1、连接池中有连接直接返回 2、连接池中无连接切设置等待时间为负数 wait无限等待 3、连接池中无连接切设置等待时间 wait
	 * 按设置时间等待,被唤醒后需要如果没有抢到锁则重新计算等待时间,重新等待
	 * 
	 * @throws InterruptedException
	 */
	public Connection getConnection(long expireMills) throws InterruptedException {

		synchronized (connectionPool) {
			// 连接池中无连接切设置等待时间为负数 wait无限等待
			if (expireMills < 0) {
				while (connectionPool.isEmpty()) {
					connectionPool.wait();
				}
				return connectionPool.removeFirst();
			} else {
				long time = System.currentTimeMillis() + expireMills;
				long waitTime = expireMills;
				while (connectionPool.isEmpty() && waitTime > 0) {
					connectionPool.wait(waitTime);
					// 重新计算
					waitTime = time - System.currentTimeMillis();
				}

				Connection connection = null;
				if (!connectionPool.isEmpty()) {
					// 从头部获取连接
					connection = connectionPool.removeFirst();
				}
				return connection;


			}

		}

	}

	class Connection  {
		
	}

}

测试代码:测试代码中使用到了一些并发工具类,后续章节会说明

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

import com.ckj.concurrent.DbPool.Connection;

/**
 * 1、初始化线程池大小 2、模拟多线程测试拿取线程池
 * 
 * @author ckj
 *
 */
public class DbPoolTest {

	static DbPool pool = new DbPool(10);

	static CountDownLatch latch; // 并发工具类,闭锁,模拟多线程并发测试

	static class PoolTest implements Runnable {

		int count;
		AtomicInteger success;
		AtomicInteger error;

		public PoolTest(int count, AtomicInteger success, AtomicInteger error) {
			this.count = count;
			this.success = success;
			this.error = error;
		}

		public void run() {
			while (count > 0) {
				try {
					// 获取线程池
					Connection connection = pool.getConnection(1000);
					if (connection != null) {
						try {
							// 模拟业务代码执行
							Thread.sleep(100);
						} finally {
							// TODO: handle finally clause
							pool.reConnection(connection);
							success.incrementAndGet();
						}
					} else {
						error.incrementAndGet();
						System.out.println(Thread.currentThread().getName() + "等待超时!");
					}

				} catch (Exception e) {
				} finally {
					count--;
				}
			}
			latch.countDown(); // 执行闭锁
		}
	}

	public static void main(String[] args) throws InterruptedException {

		latch = new CountDownLatch(50);
		AtomicInteger success = new AtomicInteger();// 原子类计数器:统计可以拿到连接的线程(后续会介绍到)
		AtomicInteger error = new AtomicInteger();// 原子类计数器:统计没有拿到连接的线程(后续会介绍到)
		for (int i = 0; i < 50; i++) {
			Thread thread = new Thread(new PoolTest(20, success, error));
			thread.start();
		}

		latch.await();
		System.out.println("总共尝试了: " + (50 * 20));
		System.out.println("拿到连接的次数:  " + success);
		System.out.println("没能连接的次数: " + error);
	}

注:在做测试的时候遇到了一个有趣的问题:

当代码执行到 pool.reConnection(connection); 之后发现下一句不执行了 也就是这句success.incrementAndGet(),当时找了半天结果发现是 DbPool 中的notifyAll(),没有加上对象导致的,在此记录一下,需要谨记wait/notify 的使用范式;

/* 归还连接,使用完连接后将连接重新放入池中 */
	/* 使用notifyAll 通知等待线程获取 */
	public void reConnection(Connection connection) {
		if (connection != null) {
			synchronized (connectionPool) {
				// 将连接放到最后
				connectionPool.addLast(connection);
				//使用错误:应该按照范式 对象.notifyAll()
				notifyAll();
			}
		}

	}

        在网上找到了一个总结线程协作的流程图,感觉总结的相当到位。
      

抛出一个问题:

yield() sleep()wait()notify()等方法对锁有何影响?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
CountDownLatch是Java并发编程中的一种同步工具类。它的作用是允许一个或多个线程等待其他线程完成操作。CountDownLatch的构造函数接收一个计数值,当计数值变为0时,等待的线程就会被唤醒。使用CountDownLatch可以实现多线程并发编程中的线程协作。 与使用join方法等待多个线程执行完毕不同,CountDownLatch相对灵活。可以通过调用countDown方法来减少计数,唤醒被阻塞的线程。这使得多个线程可以同时进行,并在一定条件下等待其他线程完成后再继续执行。 CountDownLatch一般称为闭锁或计数器,它是Java并发编程中的一种多线程同步工具。它属于AQS(AbstractQueuedSynchronizer)体系的一员,可以实现线程协作和同步操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Java线程之并发工具类](https://download.csdn.net/download/weixin_38713057/13756829)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [java线程并发之CountDownLatch](https://blog.csdn.net/weixin_42419762/article/details/116220340)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [多线程编程之 CountDownLatch](https://blog.csdn.net/jiangxiayouyu/article/details/118107977)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值