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(); } }
用Semaphore写一个多线程的限制资源获取
最新推荐文章于 2022-03-27 22:33:32 发布