import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
/**
* Semaphore示例,2个线程争抢1个信号量,第三个线程释放信号量.
* @author Administrator
*
*/
public class SemaphoreDemo {
public static void main(String[] args) throws Exception {
Semaphore se = new Semaphore(1);//一个信号量
Runnable run1 = () ->{
try {
int s=(int)(20+Math.random()*200);
Thread.sleep(s);//随机延迟.
} catch (InterruptedException e) {}
String name=Thread.currentThread().getName();
se.acquireUninterruptibly();
System.out.println(name+",acquireUninterruptibly get");
};
Runnable run2 = () ->{
try {
int s=(int)(20+Math.random()*200);
Thread.sleep(s);//随机延迟.
} catch (InterruptedException e) {}
String name=Thread.currentThread().getName();
while(!se.tryAcquire()) {//持续请求
}
System.out.println(name+",tryAcquire get");
};
Runnable run3 = () ->{
try {
int s=(int)(20+Math.random()*200);
Thread.sleep(s);//随机延迟.
} catch (InterruptedException e) {}
String name=Thread.currentThread().getName();
se.release();//释放
System.out.println(name+",release");
};
ExecutorService es = Executors.newFixedThreadPool(3);
es.submit(run1);
es.submit(run2);
es.submit(run3);
es.shutdown();
}
}
运行结果