信号量的很好的源码解析:
信号量,
1、如果只有1个大小的话,有点类似生活中的红绿灯。当你执行前,看下只有绿灯的时候,才允许执行,否则等待。
2、如果有N个大小的话,就类似银行的人工窗口,假设有20个人在等待3个窗口,则只有存在空闲窗口的时候,
才可以去一个人去办业务;而且只有有一个办完业务,释放了一个窗口后,则会唤醒等待队列里的一个人,去办理业务。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadPoolExecutor;
import static java.util.concurrent.Executors.*;
public class TestSemaphore {
public static void main(String [] args) {
Semaphore semaphore = new Semaphore(10);
ExecutorService es = newFixedThreadPool(3);
es.execute(new MyThread(semaphore, 4));
es.execute(new MyThread(semaphore, 5));
es.execute(new MyThread(semaphore, 6));
es.shutdown();
}
}
class MyThread implements Runnable {
private volatile Semaphore semaphore;
int threadCount;
public MyThread(Semaphore semaphore, int threadCount) {
this.semaphore = semaphore;
this.threadCount = threadCount;
}
@Override
public void run() {
try {
semaphore.acquire(threadCount);
System.out.println(Thread.currentThread().getName() + "执行中。。。" + threadCount);
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + "执行完。。。" + threadCount);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release(threadCount);
System.out.println(Thread.currentThread().getName() + "释放锁。。。" + threadCount);
}
}
}
执行结果:
pool-1-thread-1执行中。。。4
pool-1-thread-2执行中。。。5
pool-1-thread-1执行完。。。4
pool-1-thread-1释放锁。。。4
pool-1-thread-2执行完。。。5
pool-1-thread-2释放锁。。。5
pool-1-thread-3执行中。。。6
pool-1-thread-3执行完。。。6
pool-1-thread-3释放锁。。。6