java并发编程学习之Semaphore

7次阅读

共计 655 个字符,预计需要花费 2 分钟才能阅读完成。

作用

信号量,限制同一时间,访问特定资源的线程数量,以保证合理的使用特定资源。

主要方法

  1. acquire: 获取锁,如果没有获取到,就堵塞
  2. release: 释放锁

示例

public class SemaphoreDemo {static Semaphore semaphore = new Semaphore(2);

    static class Thread1 implements Runnable {

        @Override
        public void run() {
            try {semaphore.acquire();
                Thread.sleep(1000);
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                System.out.println(Thread.currentThread().getName() + "-" + formatter.format(new Date()));
                semaphore.release();} catch (InterruptedException e) {e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {for (int i = 0; i < 8; i++) {new Thread(new Thread1()).start();}
    }
}

运行结果如下:

可以看出,每次执行都是 2 个。
如果把 semaphore.acquire() 和 semaphore.release() 注释掉,可以看的结果如下:

同一时间,都打印到了控制台。

正文完
 0