Semaphore,译为信号量,它的作用就是维护一类可用资源,在多线程环境下保持资源竞争同步的作用。比如,一个停车场,只有三个车位,三个车位就是Semaphore,这时有10辆车要停进来,那么最多只能停进来3辆,其他的车必须等到有车离开停车场才能进去停车。直接来个程序吧。
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; public class CarParking implements Runnable { private static final int POSITION_COUNT = 2; private int idx; private Semaphore position; public static void main(String[] args) { ExecutorService parkingLot = Executors.newCachedThreadPool(); Semaphore parkingPositions = new Semaphore(3); for (int i = 0; i < 10; i++) { parkingLot.submit(new CarParking(i, parkingPositions)); } parkingLot.shutdown(); } public void run() { try { position.acquire(); pl("车" + idx + "获得一个车位,停好了!"); Thread.sleep((long)Math.random() * 1000); pl("车" + idx + "离开停车场了!"); position.release(); } catch (InterruptedException e) { e.printStackTrace(); } } public CarParking(int idx, Semaphore position) { this.idx = idx; this.position = position; } private static void pl(Object o) { System.out.println(o); } }
运行结果如下(不一定相同):
车0获得一个车位,停好了! 车2获得一个车位,停好了! 车1获得一个车位,停好了! 车2离开停车场了! 车1离开停车场了! 车0离开停车场了! 车3获得一个车位,停好了! 车4获得一个车位,停好了! 车4离开停车场了! 车3离开停车场了! 车5获得一个车位,停好了! 车7获得一个车位,停好了! 车6获得一个车位,停好了! 车7离开停车场了! 车5离开停车场了! 车8获得一个车位,停好了! 车6离开停车场了! 车8离开停车场了! 车9获得一个车位,停好了! 车9离开停车场了!
相关推荐
10. **Concurrent包中的工具类**:如Semaphore(信号量)用于限制同时访问资源的线程数量,CountDownLatch用于等待多个任务完成,CyclicBarrier用于同步多线程到达某个点。 11. **EnumSet与EnumMap**:专为枚举类型...
8. **并发编程**:`java.util.concurrent`包虽然不在`java.util`下,但与之紧密相关,提供了高级并发工具,如ExecutorService、Future、Semaphore和CyclicBarrier。 9. **事件模型**:`java.util.EventObject`和`...
这个名为“Xiaofei-it-Concurrent-Utils-829a450”的压缩包可能包含了一些优化和扩展了Java标准并发库(java.util.concurrent)的实用工具类。这里我们将深入探讨一些关于Java并发编程的关键知识点,并尝试理解这个...
Java util.concurrent包提供了丰富的并发工具类,如ExecutorService、Semaphore等。 9. **对象工具**:如ClassUtils、ReflectionUtils等,可以帮助处理类、对象的反射操作,以及类型转换等。 10. **编码解码工具**...
9. **java.util.concurrent**: 提供了线程和并发控制的工具类,如ExecutorService、Semaphore和CountDownLatch,帮助开发者实现多线程环境下的同步和异步操作。 10. **java.util.HashMap** 和 **java.util.HashSet*...
7. **并发处理**: `java.util.concurrent`包提供了丰富的并发工具,如ExecutorService、Semaphore、CyclicBarrier、CountDownLatch等,帮助开发者高效地编写多线程程序。 8. **字符串处理**: `String`类是不可变的...
4. **线程与并发**: Java.util.concurrent包提供了高级并发工具,如ExecutorService、Semaphore、CountDownLatch和CyclicBarrier,帮助开发者更有效地管理多线程环境。 5. **字符串处理**: String类是不可变的,...
Java的`java.util.concurrent`包提供了丰富的并发工具,如`ExecutorService`、`Semaphore`、`CountDownLatch`等。 以上只是部分可能包含在"日常用的工具类"中的功能,实际的工具类可能根据具体需求和项目特性有所...
concurrent.futures contextlib datetime decimal distutils email encodings enum faulthandler fileinput hashlib http.client idlelib and IDLE importlib inspect json logging math ...