场景
桥只能允许两个人,多一个人上桥就会落水,所以只能保证桥上的人流量为2人。
实现
public class SemaphoreTest {
private static final Semaphore semaphore = new Semaphore(2);
public static void main(String[] args) {
ThreadPoolExecutor tpe = new ThreadPoolExecutor(2,
2,
20,
TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(10));
tpe.allowCoreThreadTimeOut(true);
tpe.execute(new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " 上桥");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
tpe.execute(new Runnable() {
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " 上桥");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
tpe.execute(new Runnable() {
@Override
public void run() {
try {
semaphore.release();
System.out.println(Thread.currentThread().getName() + " 下桥");
semaphore.acquire();
System.out.println(Thread.currentThread().getName() + " 上桥");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
}
}
结果:
pool-1-thread-1 上桥
pool-1-thread-2 上桥
pool-1-thread-1 下桥
pool-1-thread-1 上桥
网友评论