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個(gè)協(xié)調(diào)線程間進(jìn)程的同步裝置,它們分別是:
* Semaphore, CountDownLatch, CyclicBarrier和Exchanger.
* 本例主要介紹Semaphore。
* Semaphore是用來(lái)管理一個(gè)資源池的工具,可以看成是個(gè)通行證,
* 線程要想從資源池拿到資源必須先拿到通行證,
* 如果線程暫時(shí)拿不到通行證,線程就會(huì)被阻斷進(jìn)入等待狀態(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+"等待,沒(mé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);
}
}
相關(guān)文章
jar命令修改jar包中的application.yml配置文件
本文主要介紹了jar命令修改jar包中的application.yml配置文件,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08Java基于ReadWriteLock實(shí)現(xiàn)鎖的應(yīng)用
這篇文章主要介紹了Java基于ReadWriteLock實(shí)現(xiàn)鎖的應(yīng)用,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10SpringBoot2.1.4中的錯(cuò)誤處理機(jī)制
這篇文章主要介紹了SpringBoot2.1.4中的錯(cuò)誤處理機(jī)制,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10如何在IDEA上安裝scala插件并創(chuàng)建工程(圖文教程)
這篇文章主要介紹了一文教你如何在IDEA上安裝scala插件并創(chuàng)建工程,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07Mybatis-Plus通過(guò)SQL注入器實(shí)現(xiàn)批量插入的實(shí)踐
本文主要介紹了Mybatis-Plus通過(guò)SQL注入器實(shí)現(xiàn)批量插入的實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-08-08