很久没有更新了,最近一直在学习how tomcat woks,以及java多线程,这里给学习做一个总结。
Semaphore :信号量,计算机操作系统里这么解释,所谓信号量,就是多个线程执行时,有一个信号来进行管理,比如过马路,马路有十字路口,横、竖都可以过人,这样很容易出现问题的,这时候红绿灯就是一种信号量,只允许绿灯通过、红灯等待。
java里也一样 ,来看一下jdk1.6中的描述:'
A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.
简单的说的是一个计数信号量,有两个方法,acquire()和 release()方法,acquire阻塞直到release释放一个许可信号。
我们有一段简洁的代码来解释一下:
public class TestSemaphore {
public static void main(String[] args) {
final Semaphore semaphore = new Semaphore(5);
try {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i=0; i<10; i++) {
final int index = i;
Runnable r = new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
System.out.println("running ..." + index);
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
exec.submit(r);
}
exec.shutdown();
} catch (Exception e) {
e.printStackTrace();
}
}
}