您好,欢迎来到华佗小知识。
搜索
您的当前位置:首页Java并发之Semaphore应用

Java并发之Semaphore应用

来源:华佗小知识

Semaphore意为信号量,它的使用原理跟操作系统中的PV原语非常相似,所以不再多说。下面是一个使用Semaphore的例子。

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
 
public class SemaphoreTest {
    public static void main(String[] args) {
        ExecutorService service = Executors.newCachedThreadPool();
 
        final Semaphore sp = new Semaphore(3);
        for (int i = 0; i < 10; i++) {
            Runnable runnable = new Runnable() {
                public void run() {
                    try {
                        sp.acquire();
                    } catch (InterruptedException e1) {
                        e1.printStackTrace();
                    }
                    System.out.println("Thread: "
                            + Thread.currentThread().getName()
                            + " gets in,we now have "
                            + (3 - sp.availablePermits()) + " concurrent");
                    try {
                        Thread.sleep((long) (Math.random() * 10000));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("Thread: "
                            + Thread.currentThread().getName() + " is leaving");
                    sp.release();
                }
            };
            service.execute(runnable);
        }
        service.shutdown();
    }
 
}

Copyright © 2019- huatuo0.cn 版权所有 湘ICP备2023017654号-2

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务