(1)Semaphore 案例
类Semaphore(信号灯)的同步性:
多线程中的同步概念其实就是排着队去执行一个任务,执行任务是一个一个执行,并不能并行执行,这样的有点有助于程序逻辑的正确性,不会出现非现场安全问题,保证软件在系统功能上的运行稳定性。
初步来看一个例子:
public static void main(String[] args) {
ExecutorService server = Executors.newCachedThreadPool();
final Semaphore sp=new Semaphore(3);
for(int i=0;i<10;i++){
Runnable r=new Runnable() {
@Override
public void run() {
try {
sp.acquire();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程:"+Thread.currentThread().getName()+"进入,当前已有"+(3-sp.availablePermits() )+"个并发");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程:"+Thread.currentThread().getName()+"即将离开了");
sp.release();
System.out.println("线程:"+Thread.currentThread().getName()+"离开了,还有:"+(3-sp.availablePermits()));
}
};
server.execute(r);
}
