谈谈Semaphore结合ReentrantLock保证同步
答:
下面代码说明有3个线程可以同时执行semaphore.acquire()和semaphore.release()之间的代码,但只有一个线程能处理lock.lock()和lock.unlock()之间的代码
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;
public class SemaphoreTest {
private Semaphore semaphore = new Semaphore(3);
private ReentrantLock lock = new ReentrantLock();
public void test() {
try {
semaphore.acquire();
System.out.println("ThreadName=" +Thread.currentThread().getName() + "进来了");
lock.lock();
System.out.println(Thread.currentThread().getName() + "获得了锁" );
lock.unlock();
semaphore.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}