62,615
社区成员
发帖
与我相关
我的任务
分享
package sample.concurrent;
import java.util.concurrent.Semaphore;
public class Test {
private final Semaphore available = new Semaphore(2);
public void methodA() {
try {
available.acquire();
methodB();
available.release();
} catch (InterruptedException ex) {
}
}
public void methodB() {
System.out.println(Thread.currentThread().getName() + ": " + "Entering methodB ...");
try {
Thread.sleep(3000);
} catch (InterruptedException ex) {
}
System.out.println(Thread.currentThread().getName() + ": " + "Leaving methodB ...");
}
public static void main(String[] args) {
final Test t = new Test();
for (int i = 0; i < 10; i++) {
new Thread() {
@Override
public void run() {
t.methodA();
}
}.start();
}
}
}