并发包-Semaphore实现线程的通信

来源:互联网 发布:西班牙语扫描翻译软件 编辑:程序博客网 时间:2024/05/19 22:44

作用:

维护当前资源被线程访问的个数,当达到方法指定的值后,资源类似自动的上锁,其他线程需要等待获得许可。

使用:

实例.acquire()获得许可,许可减一。
实例.release()释放许可,许可加一。

实例:

通过Semaphore维护list的访问数,list的大小维持在5个(包括5)一下。
public class test2 {static List<String> list = new ArrayList<String>();static Semaphore sem = new Semaphore(5);public static void add(String s) throws InterruptedException{boolean added = false;sem.acquire();added = list.add(s);if(!added){sem.release();}}public static void remove() throws InterruptedException{boolean removed = false;removed = list.remove("s");if(removed){sem.release();}}public static void main(String[] args){ExecutorService pool = Executors.newCachedThreadPool();CyclicBarrier barrier = new CyclicBarrier(200);for(int i = 0 ; i < 200 ; i++){Thread add = new Thread(new Runnable(){@Overridepublic void run() {try {try {barrier.await();} catch (BrokenBarrierException e) {e.printStackTrace();}test2.add("s");System.out.println("list大小:" + test2.list.size());} catch (InterruptedException e) {e.printStackTrace();}}});Thread remove = new Thread(new Runnable(){@Overridepublic void run() {try {try {barrier.await();} catch (BrokenBarrierException e) {e.printStackTrace();}test2.remove();System.out.println("list大小:" + test2.list.size());} catch (InterruptedException e) {e.printStackTrace();}}});pool.execute(add);pool.execute(remove);}pool.shutdown();}}


0 0
原创粉丝点击