作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何编写一个简单的公平锁模拟新的ReentrantLock(true)
?
public class Main1 {
public static void main(String[] args) {
// Lock lock = new ReentrantLock(true);
CustomLock lock = new CustomLock();
new Thread(new Producer(lock)).start();
new Thread(new Consumer(lock)).start();
}
}
class Producer implements Runnable {
private Lock lock;
private CustomLock customLock;
public Producer(Lock lock) {
this.lock = lock;
}
public Producer(CustomLock lock) {
this.customLock = lock;
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// lock.lock();
customLock.lock();
System.out.println("Producer before");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Producer after");
// lock.unlock();
customLock.unlock();
}
}
}
class Consumer implements Runnable {
private Lock lock;
private CustomLock customLock;
public Consumer(Lock lock) {
this.lock = lock;
}
public Consumer(CustomLock lock) {
this.customLock = lock;
}
@Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
// lock.lock();
customLock.lock();
System.out.println("Consumer before");
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Consumer after");
// lock.unlock();
customLock.unlock();
}
}
}
class CustomLock{
private boolean isLocked;
public synchronized void lock(){
while (isLocked) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isLocked = true;
}
public synchronized void unlock(){
if(isLocked){
isLocked = false;
notify();
}
}
}
自定义不公平锁(我不确定它是否正确)
class CustomLock{
private boolean isLocked;
public synchronized void lock(){
while (isLocked) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isLocked = true;
}
public synchronized void unlock(){
if(isLocked){
isLocked = false;
notify();
}
}
}
最佳答案
如果你想要一个公平的锁,你需要使用一个列表并按照列表顺序通知线程。
关于java - 如何写一个简单的公平锁?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10008774/
我有一个应用程序倾向于在后台线程中执行很多数据库 Activity (下载大型数据库更新),而且这个过程经常使“UI线程”匮乏-我知道数据库是不定期发布的,但是所使用的@synchronized机制不
我正在创建一个程序,用户可以在从一组项目中选择的两个项目之间进行一系列投票。每次投票后,会显示集合中的两个新项目并对其进行投票,直到看到集合中的所有成员。 这是我的限制条件: 每个用户应该以不同的随机
我正在开发一个在线判断类型的系统,其中大约 100 个不受信任的可执行文件将同时运行并评估相同的输入数据。 我希望每个可执行文件都限制在预定义资源池的 CPU、内存、磁盘空间等的相等份额。例如,如果资
我正在从事一个关于 CFS 的项目。使用Ftrace跟踪Linux公平进程的全路径。 根据文档 https://lwn.net/Articles/370423/ . [tracing]# echo $
Semaphore 类概述 developer.android.com看起来不错 - 对于那些已经熟悉这些概念和术语的人来说。 我熟悉那里的一些首字母缩略词和其他行话(例如 FIFO、锁等),但其他的
我是一名优秀的程序员,十分优秀!