简单实现一个java公平策略的锁

本文介绍了一个简单的自定义并发锁的实现方法,通过使用Java的LockSupport工具类来模拟线程间的锁定与解锁行为,并通过一个测试用例验证了其实现的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码是:

package com.eyu.gift.lock;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.LockSupport;

class FailLock {

Queue<Thread> queue = new ConcurrentLinkedQueue<Thread>();

public void lock() {
queue.add(Thread.currentThread());
if (queue.peek() != Thread.currentThread()) {
LockSupport.park(this);
}
}

public void unlock() {
queue.remove();
LockSupport.unpark(queue.peek());

}

}




测试代码:

package com.eyu.gift.lock;

import java.util.concurrent.CountDownLatch;

import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;

public class FailLockTest {
public static final int NUM = 5000;
public static final int THREAD_NUM = 40;
static int[] target = new int[THREAD_NUM];

@Test
public void test() throws Exception {
final FailLock failLock = new FailLock();
final CountDownLatch endCountDownLatch = new CountDownLatch(THREAD_NUM);
final CountDownLatch startCountDownLatch = new CountDownLatch(1);

for (int j = 0; j < THREAD_NUM; j++) {
final int thread = j;
Thread t = new Thread() {
@Override
public void run() {
try {
startCountDownLatch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
for (int i = 0; i < NUM; i++) {
failLock.lock();
++target[thread];
// System.err.println(target[thread] + " ======== " + Thread.currentThread().getName());
failLock.unlock();
}
endCountDownLatch.countDown();

}

};
t.setName("线程" + thread);
t.start();
}

startCountDownLatch.countDown();
endCountDownLatch.await();
int total = 0;
for (int i = 0; i < THREAD_NUM; i++) {
total += target[i];
}
Assert.assertThat(total, Matchers.is(THREAD_NUM * NUM));
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值