JAVA多线程编程实践

Semaphore

      信号量用来控制能够同时访问某特定资源的数量,或者同时执行某一给定的操作结果。

一个Semaphore管理一个有效的许可集,许可的初始化量通过构造函数传递给Semaphore。活动能够获得的许可,并在使用后释放许可。如果没有许可,accquire会阻塞,直到有可用的许可。release方法返回一个许可。

 

Semaphore的构造函数

1.Semaphore(int permits);

2.Semaphore(int permits, boolean fair)  设置是否公平 fair为true即为满足FIFO原则,false为获取线程无序。

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

public class DemoSemaphore {

	public static void main(String[] args) {
		final Semaphore semaphore = new Semaphore(2);
		ExecutorService executorService = Executors.newCachedThreadPool();
		for (int i = 1; i < 5; i++) {
			final int index = i; 
			executorService.execute(new Runnable() {
				public void run() {
					try {
						semaphore.acquire();
						System.out.println("线程:" + Thread.currentThread().getName() + "获得许可:" + index);
						// 处理相应的业务
						TimeUnit.SECONDS.sleep(1);
						semaphore.release();
						System.out.println("线程:" + Thread.currentThread().getName() + "释放许可:" + index);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			});
		}
		executorService.shutdown();
		try {
			TimeUnit.SECONDS.sleep(5);
			System.out.println( semaphore.availablePermits() + "个许可可用");  
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

 运行结果:

线程:pool-1-thread-2获得许可:2
线程:pool-1-thread-1获得许可:1
线程:pool-1-thread-1释放许可:1
线程:pool-1-thread-3获得许可:3
线程:pool-1-thread-2释放许可:2
线程:pool-1-thread-4获得许可:4
线程:pool-1-thread-3释放许可:3
线程:pool-1-thread-4释放许可:4
2个许可可用

猜你喜欢

转载自stefan-jiq.iteye.com/blog/2285773