1.信号量:
Semaphore用于保存当前允许通过的线程数量
2.实例
public class Test {
public static void main(String[] args) throws Exception {
Test test = new Test();
for (int i = 0; i < 10; i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
test.print();
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
}
Semaphore semaphore = new Semaphore(2);
private void print() throws Exception {
semaphore.acquire();
Thread.sleep(2000);
System.out.println(Thread.currentThread().getName() + " print...");
semaphore.release();
}
}
3.总结:
Semaphore实现了线程锁的功能。