Java多线程 使用信号量来控制资源获取

本文介绍了Java中如何使用信号量解决多线程资源冲突问题。信号量可以控制资源的并发访问数量,并可以选择公平模式,依据线程等待时间分配资源。
摘要由CSDN通过智能技术生成
               

在多线程开发中,有一个很经典的名词,那就是信号量。信号量就是用来衡量一个资源的可利用数目的,根据信号

量的多少来控制在多线程中各个资源之间的冲突问题,在Java中也提供了对信号量的支持。


而且在创建信号量的时候,第二个参数用来指定采取何种分配策略,比如当有很多线程被阻塞,但有一个机会的时

候,信号量应该选择谁去运行呢,如果选择true,就采用公平模式,到时候看哪个线程等待的时间最久,就把机会给那

个等待最久的线程,这样的就是公平分配策略。


下面就用代码来说明一下问题


package com.bird.concursey.charpet4;import java.util.concurrent.Semaphore;public class PrintQueue { // It initializes the semaphore object that will protect the access from the // print queue. private final Semaphore semaphore = new Semaphore(1,true); public void printJob(Object document) {  //you must acquire the semaphore calling  try {   semaphore.acquire();   long duration = (long)(Math.random()*10);   System.out.printf("%s: PrintQueue: Printing a Job during %d seconds\n",Thread.currentThread().getName(),duration);   Thread.sleep(duration);  } catch (InterruptedException e) {   e.printStackTrace();  }finally{   //free the semaphore by calling the release() method of the semaphore.   semaphore.release();  } }}



package com.bird.concursey.charpet4;public class Job implements Runnable {  private PrintQueue printQueue;  public Job(PrintQueue printQueue) {  this.printQueue = printQueue; } @Override public void run() {  System.out.printf("%s: Going to print a job\n",Thread.currentThread().getName());  printQueue.printJob(new Object());  System.out.printf("%s: The document has been printed\n",Thread.currentThread().getName()); }  public static void main(String[] args) {  PrintQueue printQueue = new PrintQueue();  Thread thread[] = new Thread[10];  for(int i = 0; i < 10; i++) {   thread[i] = new Thread(new Job(printQueue), "Thread " + i);  }  for(int i = 0; i < 10; i++) {   thread[i].start();  } }}


           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值