package Thread;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* Semaphore 控制同时访问资源的线程个数
*/
public class SemaphoreTest {
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(3);
for(int i=0; i<10; i++){
Runnable run = new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();//并发超过3,阻塞
System.out.println("线程"+Thread.currentThread().getName()+"进入 当前已有 " + (3-semaphore.availablePermits()));
TimeUnit.SECONDS.sleep(new Random().nextInt(10));
// Thread.sleep((long)(Math.random()*10000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
semaphore.release();
System.out.println("线程"+Thread.currentThread().getName()+"离开 当前已有" + (3-semaphore.availablePermits()));
}
};
pool.execute(run);
}
}
}
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/**
* Semaphore 控制同时访问资源的线程个数
*/
public class SemaphoreTest {
public static void main(String[] args) {
ExecutorService pool = Executors.newCachedThreadPool();
final Semaphore semaphore = new Semaphore(3);
for(int i=0; i<10; i++){
Runnable run = new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();//并发超过3,阻塞
System.out.println("线程"+Thread.currentThread().getName()+"进入 当前已有 " + (3-semaphore.availablePermits()));
TimeUnit.SECONDS.sleep(new Random().nextInt(10));
// Thread.sleep((long)(Math.random()*10000));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
semaphore.release();
System.out.println("线程"+Thread.currentThread().getName()+"离开 当前已有" + (3-semaphore.availablePermits()));
}
};
pool.execute(run);
}
}
}