package org.ado.test;
import java.util.*;
import java.util.concurrent.*;
public class SemApp {
public static void main(String[] args) {
Runnable limitedCall = new Runnable() {
final Random rand = new Random();
final Semaphore available = new Semaphore(3);
int count = 0;
public void run() {
int time = rand.nextInt(15);
int num = count++;
try {
available.acquire();
System.out.println("Executing "
+ "long-running action for " + time
+ " seconds... #" + num);
Thread.sleep(time * 1000);
System.out.println("Done with #" + num + "!");
available.release();
} catch (InterruptedException intEx) {
intEx.printStackTrace();
}
}
};
for (int i = 0; i < 10; i++)
new Thread(limitedCall).start();
}
}
在一些企业系统中,开发人员经常需要限制未处理的特定资源请求(线程/操作)数量,事实上,限制有时候能够提高系统的吞吐量,因为它们减少了对特定资源的争用。尽管完全可以手动编写限制代码,但使用 Semaphore 类可以更轻松地完成此任务,它将帮您执行限制
Semaphore
最新推荐文章于 2024-08-18 21:36:31 发布