您的位置:首页 > 编程语言 > Java开发

java 多线程之Semaphore互斥类的用法

2015-06-30 21:04 519 查看
public class SemaphoreTest {
public static void main(String[] args) {
ExecutorService service = Executors.newCachedThreadPool();
final  Semaphore sp = new Semaphore(3);
for(int i=0;i<10;i++){
Runnable runnable = new Runnable(){
public void run(){
try {
sp.acquire();

} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("线程" + Thread.currentThread().getName() +
"进入,当前已有" + (3-sp.availablePermits()) + "个并发");
try {
Thread.sleep((long)(Math.random()*10000));
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程" + Thread.currentThread().getName() +
"即将离开");
sp.release();
//下面代码有时候执行不准确,因为其没有和上面的代码合成原子单元
System.out.println("线程" + Thread.currentThread().getName() +
"已离开,当前已有" + (3-sp.availablePermits()) + "个并发");
}
};
service.execute(runnable);
}
}

}

打印结果如下:

线程pool-1-thread-1进入,当前已有1个并发

线程pool-1-thread-2进入,当前已有2个并发

线程pool-1-thread-4进入,当前已有3个并发

线程pool-1-thread-2即将离开

线程pool-1-thread-2已离开,当前已有2个并发

线程pool-1-thread-5进入,当前已有3个并发

线程pool-1-thread-4即将离开

线程pool-1-thread-4已离开,当前已有2个并发

线程pool-1-thread-3进入,当前已有3个并发

线程pool-1-thread-1即将离开

线程pool-1-thread-1已离开,当前已有2个并发

线程pool-1-thread-8进入,当前已有3个并发

线程pool-1-thread-8即将离开

线程pool-1-thread-8已离开,当前已有2个并发

线程pool-1-thread-7进入,当前已有3个并发

线程pool-1-thread-5即将离开

线程pool-1-thread-5已离开,当前已有2个并发

线程pool-1-thread-6进入,当前已有3个并发

线程pool-1-thread-3即将离开

线程pool-1-thread-3已离开,当前已有2个并发

线程pool-1-thread-9进入,当前已有3个并发

线程pool-1-thread-6即将离开

线程pool-1-thread-6已离开,当前已有2个并发

线程pool-1-thread-10进入,当前已有3个并发

线程pool-1-thread-7即将离开

线程pool-1-thread-7已离开,当前已有2个并发

线程pool-1-thread-9即将离开

线程pool-1-thread-9已离开,当前已有1个并发

线程pool-1-thread-10即将离开

线程pool-1-thread-10已离开,当前已有0个并发
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: