package zhu.suo;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;
/*
* Semaphore信号灯实现一个文件的并发访问
也就是限制同时访问线程数
* */
public class SemphoreDemo {
public static void main(String[] args) {
ExecutorService threadPool= Executors.newCachedThreadPool();
final Semaphore semaphore= new Semaphore(3);//设置并发线程数为3 同步信号为3
for(int i=1;i<11;i++)
{
Runnable runable = new Runnable() {
public void run() {
try {
semaphore.acquire();//获取一个信号灯 最多有三个 否则多余的阻塞
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("当前线程为:"+Thread.currentThread().getName()+"并发线程数:"+(3-semaphore.availablePermits()));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
System.out.println("线程"+Thread.currentThread().getName()+"离开");
semaphore.release();
}
}
};
threadPool.execute(runable);//新建一个runable线程就放入线程池执行
}
threadPool.shutdown();
}
}
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;
/*
* Semaphore信号灯实现一个文件的并发访问
也就是限制同时访问线程数
* */
public class SemphoreDemo {
public static void main(String[] args) {
ExecutorService threadPool= Executors.newCachedThreadPool();
final Semaphore semaphore= new Semaphore(3);//设置并发线程数为3 同步信号为3
for(int i=1;i<11;i++)
{
Runnable runable = new Runnable() {
public void run() {
try {
semaphore.acquire();//获取一个信号灯 最多有三个 否则多余的阻塞
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("当前线程为:"+Thread.currentThread().getName()+"并发线程数:"+(3-semaphore.availablePermits()));
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}finally{
System.out.println("线程"+Thread.currentThread().getName()+"离开");
semaphore.release();
}
}
};
threadPool.execute(runable);//新建一个runable线程就放入线程池执行
}
threadPool.shutdown();
}
}