Semaphore初探

 示例一:

package com.smbea.demo.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Semaphore 用于为线程加锁与释放锁
 * @author hapday
 * @2017年1月16日 @下午8:50:55
 */
public class SemaphoreTest {

	public static void main(String[] args) {
		int permissionCount = 5;	// 许可数
		ExecutorService executorService = Executors.newCachedThreadPool();
		final Semaphore semaphore = new Semaphore(permissionCount);		// 声明并实例化“许可数”为 5 的 Semaphore 实例
		
		for(int index = 0; index < 10; index++) {
			try {
				// 休眠 0.1 秒
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			Runnable runnable = new Runnable() {

				@Override
				public void run() {
					try {
						// 当前线程请求获取 semaphore 的“许可”;如果获得了 semaphore 的“许可”则此线程继续则行,并且 semaphore 的许可数减一;否则此线程进入阻塞状态。
						semaphore.acquire();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
					System.out.println("线程:" + Thread.currentThread().getName() + " 进入,当前已有 " + (permissionCount - semaphore.availablePermits()) + " 个并发线程。");
					
					try {
						Thread.sleep((long) (Math.random() * 10000));
//						Thread.sleep(10000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
					System.out.println("线程:" + Thread.currentThread().getName() + " 即将离开...");
					semaphore.release();	// 将当前的线程释放“许可数”,semaphore 的许可数加一,至于哪个线程先离开没有固定的顺序
					System.out.println("线程:" + Thread.currentThread().getName() + " 已离开,当前已有 " + (permissionCount - semaphore.availablePermits()) + " 个并发线程已离开。");
				}
				
			};
			
			executorService.execute(runnable);
		}
	}

}

  

 

示例二:

package com.smbea.demo.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Semaphore 用于为线程加锁与释放锁
 * @author hapday
 * @2017年1月16日 @下午8:50:55
 */
public class SemaphoreTest2 {

	public static void main(String[] args) {
		int permissionCount = 5;	// 许可数
		ExecutorService executorService = Executors.newFixedThreadPool(permissionCount);
		Counter counter = new Counter();
		
		for(int index = 0; index < 8; index++) {
			try {
				// 休眠 0.1 秒
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			executorService.execute(new Runnable() {

				@Override
				public void run() {
					counter.calculate();
				}
				
			});
			
		}
		
		executorService.shutdown();
		
	}

	public static class Counter {
		private int count = 0;
		Lock lock = new ReentrantLock();
		int permissionCount = 5;	// 许可数
		Semaphore semaphore = new Semaphore(permissionCount);
		
		public void calculate() {
//			lock.lock();
			try {
				// 当前的线程请求获取“锁”
				semaphore.acquire();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			try {
				count++;
					
				try {
					// 休眠 1 秒钟
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				} 

				System.out.println("线程:" + Thread.currentThread().getName() + ",count = " + count);
			} finally {
				semaphore.release(); 	// 释放当前线程的“锁”
//				lock.unlock();
			}
			
		}
	}

}

  

posted @ 2017-01-16 21:20  hapday  阅读(139)  评论(0编辑  收藏  举报