Java多线程之Semephore
来源:互联网 发布:2016年社交网络格局 编辑:程序博客网 时间:2024/04/30 02:34
Semaphore 可以维护当前访问自身的线程个数,并提供了同步机制。使用Semaphore可以控制同时访问资源的线程个数,例如,实现一个文件允许的并发访问数。
单个信号量的Semaphore对象可以实现互斥锁的功能,并且可以是由一个线程获得了“锁”,再由另一个线程释放“锁”,这可应用于死锁恢复的一些场合。
package com.javase.thread;import java.util.Random;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Semaphore;import java.util.concurrent.TimeUnit;/** * 10个线程并发访问牌数为3的信号灯 * @author Alex Zhuang * */public class SemaphoreDemo {public static void main(String[] args) {final Semaphore semaphore = new Semaphore(3);ExecutorService threadPool = Executors.newCachedThreadPool();for(int i=0;i<10;i++){Runnable command =new Runnable(){public void run() {System.out.println(Thread.currentThread().getName()+" is waiting now");try {// Acquires a permit from this semaphore, blocking until one is available, or the thread is interrupted.semaphore.acquire();} catch (InterruptedException e) {e.printStackTrace();}System.out.println(Thread.currentThread().getName()+" is running now");System.out.println("There are "+ (3-semaphore.availablePermits()) + " thread got the permit of semaphore now");try {//Java SE5 引入的更加显示的sleep()版本,这个方法允许指定sleep()延迟的时间单元,因此有更好的可读性TimeUnit.MILLISECONDS.sleep(new Random().nextInt(10000));} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}// Releases a permit, returning it to the semaphore.semaphore.release();System.out.println(Thread.currentThread().getName()+" has been end now");System.out.println("There are "+ (3-semaphore.availablePermits()) + " thread got the permit of semaphore now");}};threadPool.execute(command);}threadPool.shutdown();}}
- Java多线程之Semephore
- Java多线程之认识多线程
- Java多线程之ThreadLocal_1
- Android 之 Java 多线程
- Android 之 Java 多线程
- Java多线程之HelloWorld
- Java多线程之BlockingQueue
- Java多线程之CountDownLatch
- Java多线程之CyclicBarrier
- Java多线程之Exchanger
- Java多线程之Semaphore
- Java多线程之CountDownLatch
- Java多线程之synchronized
- Java多线程之ThreadLocal
- Java多线程之ThreadPool
- Java多线程之ThreadPool
- Java多线程之ThreadLocal
- Java多线程之synchronized
- 使用Hibernate获取最大值(max)的三种方法
- 开源dcm4chePACS
- 手工搭建vc自动构建服务器
- IBATIS In Action
- dcm4chepacs开源项目
- Java多线程之Semephore
- 笔记:虚函数
- Weblogic多机器集群的配置
- linuxC之目录读取
- c语言socket编程指南
- 更改MySQL的缺省(默认)数据库引擎
- 远程登录sql server2000出现错误及其解决方法
- java网络编程
- 巧用Chrome格式化压缩后的js文件