java多线程操作之Semaphore用法

加入开源中国的第一篇博客!
最近在学习和巩固javaSE的相关基础知识,对多线程同步的Semaphore方法总结用例如下:


package javasedemo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 *
 * @author htc
 */
public class JavaSEDemo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // 线程池
        ExecutorService exec = Executors.newCachedThreadPool();
        
        // 只能个线程同时访问
        final Semaphore semph = new Semaphore(3);
        // 模拟个客户端访问
        for (int index = 1; index < 10; index++) {
            final int NO = index;
            Runnable ru = new Runnable() {
                public void run() {
                    try {
                        // 获取许可
                        semph.acquire();
                        System.out.println("accessing: " + NO);

                        Thread.sleep((long) (Math.random() * 1000));
                        // 访问完后,释放
                        System.out.println("release: " + NO);
                        semph.release();
                    } catch (InterruptedException e) {
                    }
                }
            };
            exec.execute(ru);
        }
        // 退出线程池
        exec.shutdown();
    }

}

run:

accessing: 1

accessing: 2

accessing: 3

release: 3

accessing: 6

release: 2

accessing: 4

release: 4

accessing: 5

release: 1

accessing: 7

release: 7

accessing: 8

release: 5

accessing: 9

release: 6

release: 8

release: 9

成功构建 (总时间: 2 秒)


转载于:https://my.oschina.net/geekLight/blog/200413

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值