Semaphore线程并发 多线程
程序员文章站
2022-07-12 18:20:54
...
Semaphore 信号量-多线程:限制线程并发的数量
//过独木桥
public class GBridge {
private Semaphore sem = new Semaphore(1);
//只有一个线程能调用该方法
public void come(){
try{
sem.acquire();
System.out.println(Thread.currentThread().getName()+new Date());
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}finally{
sem.release();
}
}
public static void main(String args[]){
GBridge bridge = new GBridge();
for(int i=0;i<10;i++){
Thread person1 = new Person(bridge);
person1.start();
}
}
static class Person extends Thread{
private GBridge bridge;
public Person(GBridge bridge){
this.bridge = bridge;
}
public void run() {
bridge.come();
}
}
}
处理超时:boolean b =sem.tryAcquire(3000, TimeUnit.MILLISECONDS);
在3秒内返回true,超时返回false
//过独木桥
public class GBridge {
private Semaphore sem = new Semaphore(1);
//只有一个线程能调用该方法
public void come(){
try{
sem.acquire();
System.out.println(Thread.currentThread().getName()+new Date());
Thread.sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}finally{
sem.release();
}
}
public static void main(String args[]){
GBridge bridge = new GBridge();
for(int i=0;i<10;i++){
Thread person1 = new Person(bridge);
person1.start();
}
}
static class Person extends Thread{
private GBridge bridge;
public Person(GBridge bridge){
this.bridge = bridge;
}
public void run() {
bridge.come();
}
}
}
处理超时:boolean b =sem.tryAcquire(3000, TimeUnit.MILLISECONDS);
在3秒内返回true,超时返回false
上一篇: 线程关闭与定时任务 多线程
下一篇: jdk中的多线程 多线程