Semaphores

来源:互联网 发布:微博上最恶心的公知 编辑:程序博客网 时间:2024/04/29 10:18

用来控制可以访问资源的个数

可以acquire, release,就像lock,unlock一样,但是两者还是有区别的

1. 可以在不同的申线程中请和释放信号量,而lock,unlock只能在同一个线程中获得和释放,

2. 信号量不一定是锁定某一个资源,而是流程上的概念,比如:有A,B两个线程,B线程要等A线程完成某一任务以后再进行自己下面的步骤,这个任务 并不一定是锁定某一资源,还可以是进行一些计算或者数据处理之类。而线程互斥量则是“锁住某一资源”的概念,在锁定期间内,其他线程无法对被保护的数据进 行操作。



下面就将Semaphores应用在 限制某一连接的数量 ,只有当别的连接释放,等待连接的才能连接上去(反应了流程的概念)

import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;/* * Semaphores */public class App {public static void main(String[] args) throws InterruptedException {ExecutorService executor = Executors.newCachedThreadPool();for(int i=0; i<200; i++) {executor.submit(new Runnable(){@Overridepublic void run() {Connection.getInstance().connect();}});}executor.shutdown();executor.awaitTermination(1, TimeUnit.DAYS);}}

import java.util.concurrent.Semaphore;public class Connection {private static Connection instance = new Connection();private Semaphore sem = new Semaphore(10);private int connections = 0;private Connection() {}public static Connection getInstance() {return instance;}public void connect() {try {sem.acquire();} catch (InterruptedException e1) {e1.printStackTrace();}synchronized (this) {connections++;System.out.println("current connections: " + connections);}try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}synchronized (this) {connections--;System.out.println("current connections: " + connections);}sem.release();// 最好放在finally里面}}


0 0
原创粉丝点击