这是一道常见的面试题,如果遇到需要手写代码这种题,首先是要理清思路,再就是尽量体现出代码风格,关键次是顺序,
一、基于Semaphore
二、基于Synchronized
三、基于ReentrantLock
下面代码是用Semaphore的实现方式。
public static void main(String[] args) throws InterruptedException {
Semaphore a = new Semaphore(1);
Semaphore b = new Semaphore(0);
Semaphore c = new Semaphore(0);
ExecutorService poolService = Executors.newFixedThreadPool(3);
Integer count = 10;
poolService.execute(new Worker(a, b, "A", count));
poolService.execute(new Worker(b, c, "B", count));
poolService.execute(new Worker(c, a, "C", count));
Thread.sleep(1000);
poolService.shutdownNow();
}
public static class Worker implements Runnable {
private String key;
private Semaphore current;
private Semaphore