Java并发 六 Semaphorea

本文探讨了信号量在多线程环境下控制资源访问的作用,包括许可证机制、tryAcquire和release方法的使用,以及如何用信号量实现Mutex数据结构。

的信号量被用于阻挡到物理或逻辑资源的某些部分螺纹级别的访问。信号量包含一组许可证; 每当线程试图进入临界区时,如果有可用许可证,它需要检查信号量。

如果没有许可证(通过tryAcquire()),则不允许该线程跳入临界区; 但是,如果许可证可用,则授予访问权限,许可证计数器减少。

一旦执行线程释放临界区,则许可计数器再次增加(由release()方法完成)。

我们可以使用tryAcquire(long timeout,TimeUnit unit)方法指定获取访问权限的超时。

我们还可以检查可用许可证的数量或等待获取信号量的线程数。

以下代码片段可用于使用实现信号量:

static Semaphore semaphore = new Semaphore(10);
 
public void execute() throws InterruptedException {
 
    LOG.info("Available permit : " + semaphore.availablePermits());
    LOG.info("Number of threads waiting to acquire: " + 
      semaphore.getQueueLength());
 
    if (semaphore.tryAcquire()) {
        semaphore.acquire();
        // ...
        semaphore.release();
    }
 
}

我们可以使用Semaphore实现类似Mutex的数据结构。有关这方面的更多细节可以在这里找到。

package 操作系统实验二; import java.util.concurrent.*; class PrintTask implements Runnable { private char ch; private Semaphore currentSemaphore; private Semaphore nextSemaphore; public PrintTask(char ch, Semaphore currentSemaphore, Semaphore nextSemaphore) { this.ch = ch; this.currentSemaphore = currentSemaphore; this.nextSemaphore = nextSemaphore; } public void run() { try { for (int i = 0; i < 3; i++) { currentSemaphore.acquire(); System.out.print(ch); nextSemaphore.release(); } } catch (InterruptedException e) { e.printStackTrace(); } } } public class Main { public static void main(String[] args) { Semaphore semaphoreA = new Semaphore(1); Semaphore semaphoreB = new Semaphore(0); PrintTask printA = new PrintTask('A', semaphoreA, semaphoreB); PrintTask printB = new PrintTask('B', semaphoreB, semaphoreA); ExecutorService executorService = Executors.newFixedThreadPool(2); // 顺序1:AAAB executorService.execute(printA); executorService.execute(printA); executorService.execute(printA); executorService.execute(printB); // 顺序2:BBAA //executorService.execute(printB); //executorService.execute(printB); //executorService.execute(printA); //executorService.execute(printA); // 顺序3:AABA //executorService.execute(printA); //executorService.execute(printA); //executorService.execute(printB); //executorService.execute(printA); // 顺序4:ABAA //executorService.execute(printA); //executorService.execute(printB); //executorService.execute(printA); //executorService.execute(printA); executorService.shutdown(); } }
06-01
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值