package test; import org.omg.PortableServer.THREAD_POLICY_ID; import java.util.ArrayList; import java.util.List; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.Semaphore; /*** * 操作共享资源的时候,限定可以有多少可以同时执行 * 例如:停车场有10个位置 * 保安 依次放进去 10辆车,第11量车就等待。 * 过来一段时间,有3辆车开走了, * 保安可以再放进来三辆车进来 * */ public class SempreTest { Semaphore semaphore = new Semaphore(3); public void test(){ System.out.println(Thread.currentThread().getName()); } public static void main(String[] args) throws InterruptedException { final SempreTest test = new SempreTest(); List<Thread> list = new ArrayList<Thread>(); for (int i = 0; i <7 ; i++) { Thread thread1 = new Thread(new Runnable() { public void run() { System.out.println(Thread.currentThread().getName()+"进入等待"); try { test.semaphore.acquire(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+"即将执行目标代码"); test.test(); try { System.out.println(Thread.currentThread().getName()+"处理复杂业务逻辑开始~~~~~~"); Thread.sleep(20000); System.out.println(Thread.currentThread().getName()+"处理复杂业务逻辑结束~~~~~~"); } catch (InterruptedException e) { e.printStackTrace(); } test.semaphore.release(); } }); list.add(thread1); } Thread.sleep(1000); for (Thread thread : list) { Thread.sleep(100); thread.start(); } } }
java Semaphore
最新推荐文章于 2022-03-05 18:48:25 发布