并发编程-并发工具类(四)

4、Semaphore 信号量

Semaphore 是用来控制同时访问特定资源的线程数量的,可以协调各个线程保证合理的使用公共资源。从以下代码可以看的出来Semaphore 可以作流量控制,其构造方法Semaphore(int permits)用于表示许可证(流量大小)数量。

import java.util.concurrent.Semaphore;
/**
 * Semaphore 信号量演示类
 * @author ckj
 *
 */
public class SemaphoreTest {

	static Semaphore semaphore = new Semaphore(1);

	
	/* acquire():获取许可证
	 * release():归还许可证
	 * intavailablePermits():返回此信号量中当前可用的许可证数。 
	 * intgetQueueLength():返回正在等待获取许可证的线程数。
	 * booleanhasQueuedThreads():是否有线程正在等待获取许可证
	 * void reducePermit(s int reduction):减少 reduction 个许可证,是个 protected方法。
     * Collection getQueuedThreads():返回所有等待获取许可证的线程集合,是个 protected 方法
	 */
	public static void main(String[] args) throws InterruptedException {
		// 当前Semaphore 令牌为1个
		// 通过acquire方法获取了1个令牌,当前令牌为0;
		semaphore.acquire();
		System.out.println("可用令牌数:" + semaphore.availablePermits());

		// 令牌为0 通过acquire 获取的话 会被阻塞
		semaphore.acquire();
		System.out.println("可用令牌数:" + semaphore.availablePermits());

		// 通过release方法归还1个令牌,当前令牌为1;
		semaphore.release();
		System.out.println("可用令牌数:" + semaphore.availablePermits());

	}

}

下面使用Semaphore 实现一个数据库连接池,在前面的文章中使用wait/notity 实现过一次。


import java.util.LinkedList;
import java.util.concurrent.Semaphore;

/**
 * 使用Semaphore实现一个简单的数据库连接池
 * 
 * @author ckj
 *
 */
public class DbPool {
	/* 定义一个容器用做数据库连接池,由于数据库连接多做获取与释放操作所有选用LinkedList,池化技术与队列技术会在后续章节演示 */
	public LinkedList<Connection> connectionPool = new LinkedList<Connection>();
	private  Semaphore semaphore ;
	
	public DbPool(int poolSize) {
		if (poolSize > 0) {
			for (int i = 0; i < poolSize; i++) {
				connectionPool.addLast( new Connection());
			}
			semaphore = new Semaphore(poolSize);

		}
	}

	/* 归还连接,使用完连接后将连接重新放入池中 */
	public void reConnection(Connection connection) {
		if (connection != null) {
			synchronized (connectionPool) {
				// 将连接放到最后
				connectionPool.addLast(connection);
			}
			//不放在同步块里面,保证同步块颗粒度
			semaphore.release();
		}

	}

	/**
	 *由于acquire() 没有设置超时时间,设置超时时间的参数就不需要了
	 *
	 * 
	 * @throws InterruptedException
	 */
	public Connection getConnection() throws InterruptedException {
		semaphore.acquire();
		Connection connection =null;
		synchronized (connectionPool) {
			connection = connectionPool.removeFirst();
		}
		return connection;

	}

	class Connection  {
		
	}

}

测试代码依然使用前面文章使用过的测试类,稍微做了修改


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

import com.ckj.concurrent.tools.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 {
					long start = System.currentTimeMillis();
					// 获取线程池
					Connection connection = pool.getConnection();
					if (connection != null) {
						System.out.println("Thread_"+Thread.currentThread().getId()
								+"_获取数据库连接共耗时【"+(System.currentTimeMillis()-start)+"】ms.");
						try {
							Random r = new Random();//让每个线程持有连接的时间不
							// 模拟业务代码执行
							Thread.sleep(100+r.nextInt(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);
	}

}

稍微改造下让他变得更像线程池,添加可用跟已用线程池


import java.util.LinkedList;
import java.util.concurrent.Semaphore;

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

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

		}
	}

	/* 归还连接,使用完连接后将连接重新放入池中 */
	public void reConnection(Connection connection) throws InterruptedException {
		if (connection != null) {
			semaphoreless.acquire();
			System.out.println("当前有" + semaphoreful.getQueueLength() + "个线程等待数据库连接!!" + "可用连接数:"
					+ semaphoreful.availablePermits());
			synchronized (connectionPool) {
				// 将连接放到最后
				connectionPool.addLast(connection);
			}
			// 不放在同步块里面,保证同步块颗粒度,增加semaphoreless.acquire() 阻塞
			semaphoreful.release();
		}

	}

	/**
	 * 由于acquire() 没有设置超时时间,设置超时时间的参数就不需要了
	 *
	 * 
	 * @throws InterruptedException
	 */
	public Connection getConnection() throws InterruptedException {
		semaphoreful.acquire();
		Connection connection = null;
		synchronized (connectionPool) {
			connection = connectionPool.removeFirst();
		}
		semaphoreless.release();
		return connection;

	}

	class Connection {

	}

}

最近网上看到一个面试题,说有三个线程t1,t2,t3 如何保证按顺序执行。我们想到的是使用join 方法。其实如果用Semaphore 一样可以实现


import java.util.concurrent.Semaphore;

public class SemaphoreSort {
	
	static Semaphore semaphore = new Semaphore(1);
	
	static class T1 extends Thread{

		public void run() {
			System.out.println("执行t1");
			semaphore.release();
			
		}
		
	}
	
	static class T2 extends Thread{

		public void run() {
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println("执行t2");
			semaphore.release();
			
		}
		
	}
	
	static class T3 extends Thread{

		public void run() {
			System.out.println("执行t3");
			semaphore.release();
			
		}
		
	}
	
	public static void main(String[] args) throws InterruptedException {
		semaphore.acquire();
		new T1().start();
		semaphore.acquire();
		new T2().start();
		semaphore.acquire();
		new T3().start();
	}

}

解法多种多样,随手写了一个,不要嫌弃!

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值