Semaphore
在坑全部占满的情况下,哪个线程先完事儿,释放锁,剩余几个线程就抢锁,类似于停车场
案例:
package Lock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import javax.swing.text.html.HTMLDocument.HTMLReader.SpecialAction;
//信号灯
public class SemaphoreTest {
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
//三个坑
final Semaphore semaphore = new Semaphore(3);
for(int i = 0;i<10;i++)
{
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
//获取许可
semaphore.acquire();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("线程"+Thread.currentThread().getName()
+"进入,当前已有"+(3-semaphore.availablePermits()+"被使用"));
try {
Thread.sleep((long)(Math.random()*10000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("线程"+Thread.currentThread().getName()+"即将离开");
//释放一个坑,走一个线程
semaphore.release();
System.out.println("线程"+Thread.currentThread().getName()+
"已经离开,当前已有"+(3-semaphore.availablePermits()+"被使用"));
}
};
executorService.execute(runnable);
}
}
}
结果:
线程pool-1-thread-1进入,当前已有3被使用
线程pool-1-thread-3进入,当前已有3被使用
线程pool-1-thread-2进入,当前已有3被使用
线程pool-1-thread-3即将离开
线程pool-1-thread-4进入,当前已有3被使用
线程pool-1-thread-3已经离开,当前已有3被使用
线程pool-1-thread-2即将离开
线程pool-1-thread-5进入,当前已有3被使用
线程pool-1-thread-2已经离开,当前已有3被使用
线程pool-1-thread-1即将离开
线程pool-1-thread-1已经离开,当前已有2被使用
线程pool-1-thread-6进入,当前已有3被使用
线程pool-1-thread-4即将离开
线程pool-1-thread-4已经离开,当前已有2被使用
线程pool-1-thread-7进入,当前已有3被使用
线程pool-1-thread-6即将离开
线程pool-1-thread-6已经离开,当前已有2被使用
线程pool-1-thread-8进入,当前已有3被使用
线程pool-1-thread-8即将离开
线程pool-1-thread-9进入,当前已有3被使用
线程pool-1-thread-8已经离开,当前已有3被使用
线程pool-1-thread-5即将离开
线程pool-1-thread-10进入,当前已有3被使用
线程pool-1-thread-5已经离开,当前已有3被使用
线程pool-1-thread-7即将离开
线程pool-1-thread-7已经离开,当前已有2被使用
线程pool-1-thread-10即将离开
线程pool-1-thread-10已经离开,当前已有1被使用
线程pool-1-thread-9即将离开
线程pool-1-thread-9已经离开,当前已有0被使用