遇到的一个笔试,做个记录,(让你只实现handle方法内容,来控制访问doHandle方法最多只有3个线程数),
如果不是定好只能在handle方法实现,
可以用线程池,或者Semaphore(信号量)来控制执行的线程数
/**
- 初始化一个信号量为3,默认是false 非公平锁, 模拟3个停车位
*/
//这个要全局,题目没有给,所以没法用这个方法
Semaphore semaphore = new Semaphore(3, false);
//下面是handle里面的方法
semaphore.acquire(); // 抢占
doHandle(threadNum,currently);
semaphore.release();
public class ProcessLimitor {
private final Integer maxProcess = 3;
private Integer currently = 0;
public void handle(int threadNum)throws InterruptedException{
synchronized (this){
while (currently >= maxProcess){
this.wait();
}
currently++;
}
System.out.println(Thread.currentThread().getName());
doHandle(threadNum,currently);
synchronized (this){
currently--;
this.notifyAll();
}
}
private void doHandle(int threadNum,int currently)throws InterruptedException{
Thread.sleep(5000);
}
public static void main(String[] args) {
final ProcessLimitor limitor = new ProcessLimitor();
for (int i = 0;i<20;i++){
final int threadNum = i;
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
limitor.handle(threadNum);
}catch (Exception e){
e.printStackTrace();;
}
}
});
t.start();
}
}
}