涉及到操作系统中的多线程并发操作
知识点
1. Semaphore(信号量),维护一个许可集,同一时间最多允许多少线程去访问资源
线程可以通过acquire()拿到许可,或release()归还许可
如果许可全部发放分配,则其他线程进入等待状态
2. ReentrantLock[],可重入锁,类似于synchronized
独占锁且可重入的
class DiningPhilosophers { private final ReentrantLock[] lock = { new
ReentrantLock(true), new ReentrantLock(true), new ReentrantLock(true), new
ReentrantLock(true), new ReentrantLock(true), }; private Semaphore limit = new
Semaphore(4); public DiningPhilosophers() { } // call the run() method of any
runnable to execute its code public void wantsToEat(int philosopher, Runnable
pickLeftFork, Runnable pickRightFork, Runnable eat, Runnable putLeftFork,
Runnable putRightFork) throws InterruptedException { int l = philosopher; int r
= (philosopher+1)%5; limit.acquire(); lock[l].lock(); lock[r].lock();
pickLeftFork.run(); pickRightFork.run(); eat.run(); putLeftFork.run();
putRightFork.run(); lock[l].unlock(); lock[r].unlock(); limit.release(); } }