涉及到操作系统中的多线程并发操作

知识点

 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(); } }

技术
今日推荐
PPT
阅读数 126
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信