-
概念: semaphore字面意思信号量,用来控制同时访问的线程数,通过acquire()获取一个许可,如果没有就等待,release()释放一个许可。
-
例子:学校厕所有3个坑位,现在有10个学生上厕所
import java.util.concurrent.Semaphore;
public class SemaphoreTest {
public static void main(String[] args) {
Semaphore sp = new Semaphore(3);
for (int i = 0; i < 10; i++) {
new Thread(new Student(sp, "学生" + i)).start();
}
}
}
class Student implements Runnable {
private Semaphore sp;
private String name;
public Student(Semaphore sp, String name) {
this.sp = sp;
this.name = name;
}
@Override
public void run() {
try {
sp.acquire();
System.out.println(name + " 进入厕所");
Thread.sleep((long) (Math.random() * 1000));
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(name + " ------->上完厕所");
sp.release();
}
}
}
学生0 进入厕所
学生1 进入厕所
学生2 进入厕所
学生2 ------->上完厕所
学生3 进入厕所
学生1 ------->上完厕所
学生4 进入厕所
学生3 ------->上完厕所
学生5 进入厕所
学生5 ------->上完厕所
学生6 进入厕所
学生4 ------->上完厕所
学生7 进入厕所
学生0 ------->上完厕所
学生8 进入厕所
学生6 ------->上完厕所
学生9 进入厕所
学生8 ------->上完厕所
学生7 ------->上完厕所
学生9 ------->上完厕所