Semaphore信号量

Posted on 2019-11-03 21:02  FLGB  阅读(180)  评论(0编辑  收藏  举报
public class SemaphoreDemo {
    public static void main(String[] args) {
         Semaphore semaphore = new Semaphore(3);//信号量3个
         for (int i = 0; i < 6; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"抢占到资源");
                    try {
                        TimeUnit.MICROSECONDS.sleep(400);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName()+"释放了资源");
                } catch (InterruptedException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }finally{
                    semaphore.release();
                }
            },String.valueOf(i)).start();
        }
    }
}

执行结果:

1抢占到资源
2抢占到资源
0抢占到资源
2释放了资源
0释放了资源
1释放了资源
4抢占到资源
3抢占到资源
5抢占到资源
3释放了资源
5释放了资源
4释放了资源

 

Copyright © 2024 FLGB
Powered by .NET 9.0 on Kubernetes