java semaphore(0)_Java 信号量 Semaphore使用方法详解

Semaphore, 它负责协调各个线程, 以保证它们能够正确、合理的使用公共资源。也是操作系统中用于控制进程同步互斥的量,下面我们来看看Java 信号量 Semaphore使用方法

在用Semaphore 信号量的时候,感觉对公平调度比较有用,可以控制多线程争夺资源时候,最大可以几个在执行,随手写了代码测试下,如下:

说明:

1. acquire() 获取一个许可,如果没有就等待

2. release() 释放一个许可

3. Semaphore可以控制某个资源可被同时访问的个数,自行初始化的数量,为1当然就顺序执行了

package com.i5a6.semp.test;

import java.util.Random;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Semaphore;

public class SemaphoreTest {

private Semaphore semp;

private ExecutorService executorPool;

public SemaphoreTest(int threadNum) {

semp = new Semaphore(threadNum);

executorPool = Executors.newFixedThreadPool(threadNum);

}

public void doEnd() {

this.executorPool.shutdown();

}

public void doMsg(int num) {

try {

semp.acquire();

executorPool.execute(new HelloUExecutor(num));

} catch (InterruptedException e) {

e.printStackTrace();

}

}

class HelloUExecutor implements Runnable {

private int num;

public HelloUExecutor(int num) {

this.num = num;

}

Random r = new Random();

@Override

public void run() {

try {

System.out.println(num);

Thread.sleep(r.nextInt(1000));

} catch (Exception e) {

e.printStackTrace();

} finally {

semp.release();

}

}

}

public static void main(String[] args) {

// 初始化为1 顺序执行

SemaphoreTest st = new SemaphoreTest(5);

for (int i = 0; i < 20; i ) {

st.doMsg(i);

}

st.doEnd();

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值