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();
    }
 
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容