public class MyLock2 implements Lock {
private AtomicInteger state = new AtomicInteger(0);
private Thread currentThread = null;
Node head = null;
Node tail = null;
Sync sync;
private class Node {
Thread t;
Node prev;
Node next;
Node() {
}
Node(Thread t) {
this.t = t;
}
}
public MyLock2() {
sync = new NonFairLock();
}
public MyLock2(boolean fair) {
if (fair) sync = new FairLock();
else sync = new NonFairLock();
}
class Sync {
public boolean tryLock() {
if (state.compareAndSet(0, 1)) {
currentThread = Thread.currentThread();
return true;
} else if (currentThread == Thread.currentThread()) {
state.addAndGet(1);
return true;
}
return false;
}
public void lock() {
if (!tryLock()) {
Node node = new Node(Thread.currentThread());
addWaiters(node);
for (; ; ) {
if (node == head && tryLock()) {
removeHead();
return;
} else {
LockSupport.park();
}
}
}
}
public void unlock() {
if (currentThread != Thread.currentThread()) {
throw new RuntimeException("非法调用");
}
if (state.decrementAndGet() == 0 && head != null) {
LockSupport.unpark(head.t);
}
}
}
class FairLock extends Sync {
public void lock() {
if (state.get() != 0) {
Node node = new Node(Thread.currentThread());
addWaiters(node);
for (; ; ) {
if (node == head && tryLock()) {
removeHead();
return;
} else {
LockSupport.park();
}
}
} else {
tryLock();
}
}
}
class NonFairLock extends Sync {
}
@Override
public void lock() {
sync.lock();
}
@Override
public void lockInterruptibly() throws InterruptedException {
}
@Override
public boolean tryLock() {
return false;
}
@Override
public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
return false;
}
@Override
public void unlock() {
sync.unlock();
}
@Override
public Condition newCondition() {
return null;
}
private void addWaiters(Node node) {
if (tail == null) {
head = node;
tail = node;
} else {
tail.next = node;
node.prev = tail;
tail = tail.next;
}
}
private void removeHead() {
head = head.next;
if (head == null) tail = null;
}
public static void main(String[] args) {
MyLock2 lock = new MyLock2(true);
Thread thread1 = new Thread(() -> {
lock.lock();
System.out.println("thread1");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
});
Thread thread2 = new Thread(() -> {
lock.lock();
System.out.println("thread2");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
lock.unlock();
});
thread1.start();
thread2.start();
}
}
Java手写锁Lock(公平、非公平)
最新推荐文章于 2022-02-22 19:13:15 发布