java線程並發semaphore類示例。本站提示廣大學習愛好者:(java線程並發semaphore類示例)文章只能為提供參考,不一定能成為您想要的結果。以下是java線程並發semaphore類示例正文
package com.yao;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* Java 5.0裡新加了4個調和線程間過程的同步裝配,它們分離是:
* Semaphore, CountDownLatch, CyclicBarrier和Exchanger.
* 本例重要引見Semaphore。
* Semaphore是用來治理一個資本池的對象,可以算作是個通行證,
* 線程要想從資本池拿到資本必需先拿到通行證,
* 假如線程臨時拿不到通行證,線程就會被阻斷進入期待狀況。
*/
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);
}
}