1.信号量:
Semaphore用于保存当前允许通过的线程数量
2.实例
public class Test {
public static void main(String[] args) throws Exception {
Test test = new Test();
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
test.print();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
Semaphore semaphore = new Semaphore(2);
private void print() throws Exception {
semaphore.acquire();
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " print...");
semaphore.release();
}
}
3.总结:
Semaphore实现了线程锁的功能。
本文介绍了信号量Semaphore的概念及其在多线程并发控制中的应用。通过一个具体的Java示例,展示了如何使用Semaphore来限制同时访问共享资源的线程数量,从而避免资源竞争导致的问题。

被折叠的 条评论
为什么被折叠?



