package cn.tool;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaphoneTest {
/**
*Semaphone可以维护当前访问自身的线程个数,并提供了同步机制。
* 使用Semaphone可以控制当前访问资源的线程的个数。例如,实现一个文件的并发访问数。
*/
/**
* 创建一个线程池,里面有10个线程。Semaphone中只允许三个线程访问
* Semaphone 没有互斥锁的作用。
*/
public static void main(String[] args) {
ExecutorService pool=Executors.newCachedThreadPool();
final Semaphore sa=new Semaphore(3);
for(int i=0;i<10;i++){
Runnable ren=new Runnable(){
@Override
public void run() {
try {
sa.acquire();
for(int i=0;i<4;i++){
Thread.sleep(50);
System.out.println(Thread.currentThread().getName()+" "+i);
}
sa.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
pool.execute(ren);
}
}
}
运行结果如下:
从结果可以看出,同时有三个线程在并发执行,但这三个线程并没有加互斥锁,所以结果交替输出。
pool-1-thread-1 0
pool-1-thread-2 0
pool-1-thread-6 0
pool-1-thread-1 1
pool-1-thread-2 1
pool-1-thread-6 1
pool-1-thread-1 2
pool-1-thread-2 2
pool-1-thread-6 2
pool-1-thread-1 3
pool-1-thread-2 3
pool-1-thread-6 3
pool-1-thread-3 0
pool-1-thread-5 0
pool-1-thread-4 0
pool-1-thread-3 1
pool-1-thread-5 1
pool-1-thread-4 1
pool-1-thread-3 2
pool-1-thread-5 2
pool-1-thread-4 2
pool-1-thread-3 3
pool-1-thread-5 3
pool-1-thread-4 3
pool-1-thread-7 0
pool-1-thread-9 0
pool-1-thread-8 0
pool-1-thread-7 1
pool-1-thread-9 1
pool-1-thread-8 1
pool-1-thread-7 2
pool-1-thread-9 2
pool-1-thread-8 2
pool-1-thread-7 3
pool-1-thread-9 3
pool-1-thread-8 3
pool-1-thread-10 0
pool-1-thread-10 1
pool-1-thread-10 2
pool-1-thread-10 3