@RestController
@RequestMapping
public class AController {
@Autowired
private ILabelService iLabelService;
private final Semaphore semaphore = new Semaphore(5);
@RequestMapping("/semaphore")
public void semaphore(){
for(int i=0;i<1000;i++){
Thread thread = new Thread(()->{
try {
semaphore.acquire();
System.out.println("abc");
Thread.sleep(1000*60);
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
semaphore.release();
}
});
thread.start();
}
}
}
semaphore可以限制线程的并发数量。对于非常耗时消耗CPU的操作我们可以使用semaphore。这样可以限制使用的次数。(同一个方法)
@RestController
@RequestMapping
public class AController {
@Autowired
private ILabelService iLabelService;
private final Semaphore semaphore = new Semaphore(5);
@RequestMapping("/semaphore")
public void semaphore() {
try {
semaphore.acquire();
System.out.println("abc");
Thread.sleep(1000*60);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
}
}
针对多个用户同时调用的情况。