信号量用来控制能够同时访问的此时:
Semaphore semphore = new Semaphore(3);
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
semphore.acquire();
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
Random random = new Random();
Thread.sleep(random.nextInt(1000)+1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("thread1 一次循环开始");
try {
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("thread1 一次循环结束");
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
while(true) {
try {
semphore.acquire();
} catch (InterruptedException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
Random random = new Random();
Thread.sleep(random.nextInt(1000)+1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("thread2 一次循环开始");
try {
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("thread2 一次循环结束");
}
}
});
thread1.start();
thread2.start();
打印结果如下:
thread1 一次循环开始
thread1 一次循环结束
thread2 一次循环开始
thread2 一次循环结束
thread1 一次循环开始
thread1 一次循环结束
可以看到,在不释放信号量的情况下,最多进入三次。