Semaphore用法
- 1、Semaphore翻译成字面意思为 信号量,Semaphore可以控同时访问的线程个数,通过 acquire() 获取一个许可,如果没有就等待,而 release() 释放一个许可。
- 2、Semaphore类位于java.util.concurrent包下,它提供了2个构造器:
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
public Semaphore(int permits, boolean fair) {
sync = (fair)? new FairSync(permits) : new NonfairSync(permits);
}
- 3、Semaphore类中比较重要的几个方法,首先是acquire()、release()方法:
public void acquire() throws InterruptedException { }
public void acquire(int permits) throws InterruptedException { }
public void release() { }
public void release(int permits) { }
acquire()用来获取一个许可,若无许可能够获得,则会一直等待,直到获得许可。
release()用来释放许可。注意,在释放许可之前,必须先获获得许可。
这4个方法都会被阻塞,如果想立即得到执行结果,可以使用下面几个方法
public boolean tryAcquire() { };
public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException { };
public boolean tryAcquire(int permits) { };
public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException { };
假若一个工厂有5台机器,但是有8个工人,一台机器同时只能被一个工人使用,只有使用完了,
其他工人才能继续使用。那么我们就可以通过Semaphore来实现:【acquire 是阻塞式等待获得执行许可】
public class Test {
public static void main(String[] args) {
int N = 8;
Semaphore semaphore = new Semaphore(5);
for(int i=0;i<N;i++)
new Worker(i,semaphore).start();
}
static class Worker extends Thread{
private int num;
private Semaphore semaphore;
public Worker(int num,Semaphore semaphore){
this.num = num;
this.semaphore = semaphore;
}
@Override
public void run() {
try {
semaphore.acquire();
System.out.println("工人"+this.num+"占用一个机器在生产...");
Thread.sleep(2000);
System.out.println("工人"+this.num+"释放出机器");
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}