java多线程信号量

xiaoxiao2021-02-27  136

信号量解决了锁一次只能让一个线程访问资源的问题,信号量可以指定多个线程,同时访问一个资源。acquire()方法会尝试获得许可,若无法获得,则继续等待,直到获得许可。访问结束后,释放资源。 public class SemapDemo implements Runnable { final Semaphore semp=new Semaphore(5); @Override public void run() { // TODO Auto-generated method stub try { semp.acquire(); Thread.sleep(2000); System.out.println(Thread.currentThread().getName()+"done"+System.currentTimeMillis()/1000); semp.release(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { ExecutorService exec=Executors.newFixedThreadPool(15); final SemapDemo semapDemo=new SemapDemo(); for(int i=0;i<15;i++) { exec.submit(semapDemo); } } }
转载请注明原文地址: https://www.6miu.com/read-15070.html

最新回复(0)