用Semaphore写一个多线程的限制资源获取

本文介绍了一个基于Java实现的售票系统案例,通过信号量(Semaphore)来限制并发访问的数量,确保系统的稳定运行。该系统创建了多个线程模拟用户购票行为,并利用信号量控制同时进行购票操作的线程数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package shenqi.proxy;


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

/**
 * Created by shenqi on 18/5/14.
 */

public class Test{


  class SemaphoreRunnable implements Runnable{
    private Semaphore semaphore;
    private int user;

  public SemaphoreRunnable(Semaphore s,int i){
    this.semaphore = s;
    this.user = i;
  }


    @Override
  public void run(){
    try {
      //获取信号量许可
      semaphore.acquire();
      System.out.println("用户" + user + "正在买票");
      Thread.sleep((long)Math.random()*1000);
      System.out.println("用户" + user + "买完了票");
      semaphore.release();
    }catch (Exception e){
      e.printStackTrace();
    }
  }
  }


  private void getTicket(){
    final Semaphore semaphore = new Semaphore(2);
    ExecutorService executorService = Executors.newCachedThreadPool();
    for(int i = 0;i<20;i++){
      executorService.execute(new SemaphoreRunnable(semaphore,(i+1)));
    }
    executorService.shutdown();
  }

  public static void main(String [] args){
    Test t = new Test();
    t.getTicket();
  }

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值