java線程并發(fā)semaphore類示例
package com.yao;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* Java 5.0里新加了4個協(xié)調(diào)線程間進程的同步裝置,它們分別是:
* Semaphore, CountDownLatch, CyclicBarrier和Exchanger.
* 本例主要介紹Semaphore。
* Semaphore是用來管理一個資源池的工具,可以看成是個通行證,
* 線程要想從資源池拿到資源必須先拿到通行證,
* 如果線程暫時拿不到通行證,線程就會被阻斷進入等待狀態(tài)。
*/
public class MySemaphore extends Thread {
private int i;
private Semaphore semaphore;
public MySemaphore(int i,Semaphore semaphore){
this.i = i;
this.semaphore = semaphore;
}
public void run(){
if(semaphore.availablePermits() > 0){
System.out.println(""+i+"有空位 : ");
}else{
System.out.println(""+i+"等待,沒有空位 ");
}
try {
semaphore.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(""+i+"獲得空位");
try {
Thread.sleep((int)Math.random()*10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(""+i+"使用完畢");
semaphore.release();
}
public static void main(String[] args) {
Semaphore semaphore = new Semaphore(2);
ExecutorService service = Executors.newCachedThreadPool();
for(int i = 0 ;i<10 ; i++){
service.execute(new MySemaphore(i,semaphore));
}
service.shutdown();
semaphore.acquireUninterruptibly(2);
System.out.println("使用完畢,需要清掃了");
semaphore.release(2);
}
}
相關文章
猜你不知道Spring Boot的幾種部署方式(小結(jié))
這篇文章主要介紹了猜你不知道Spring Boot的幾種部署方式(小結(jié)),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-07-07
SpringBoot+?Sharding?Sphere?輕松實現(xiàn)數(shù)據(jù)庫字段加解密功能
在Spring?Boot生態(tài)中,有一個非常厲害的開源框架:Apache?ShardingSphere,它是一款分布式?SQL?事務和查詢引擎,可通過數(shù)據(jù)分片、彈性伸縮、加密等能力對任意數(shù)據(jù)庫進行增強,今天通過這篇文章,我們一起來了解一下如何在?Spring?Boot?中快速實現(xiàn)數(shù)據(jù)的加解密功能2024-07-07
Java并發(fā)編程Lock?Condition和ReentrantLock基本原理
這篇文章主要介紹了Java并發(fā)編程Lock?Condition和ReentrantLock基本原理,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-09-09
解析java稀疏數(shù)組如何幫助我們節(jié)省內(nèi)存提升性能
這篇文章主要為大家介紹了java稀疏數(shù)組如何幫助我們節(jié)省內(nèi)存提升性能解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11

