首先 自定义一个锁,我们可以实现Lock接口;lock接口源码如下:
package java.util.concurrent.locks;
import java.util.concurrent.TimeUnit;
public interface Lock {
void lock();
void lockInterruptibly() throws InterruptedException;
boolean tryLock();
boolean tryLock(long time, TimeUnit unit) throws InterruptedException;
void unlock();
Condition newCondition();
}
我们这里简单实现 两个方法lock 和unlock,保证外部可以加锁和解锁,加锁的方式,我们可以利用Synchonized关键字,
1.需要一个标识,判断是否加锁了
2.如果加锁了,那么其他线程必须等待
3.如果解锁了,其他线程应该不等待
public class MyLock implements Lock {
private boolean isLocked = false;
@Override
public synchronized void lock() {
while (isLocked) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isLocked = true;
}
@Override
public synchronized void unlock() {
isLocked = false;
notify();
}
...
}
这样我们就实现了一个锁;
但是会有如下问题,也就是不能重入,何为重入,简单理解场景在锁嵌套的时候,将不能继续执行,看下面的例子
private static class Sequence {
MyReentrantLock myReentrantLock = new MyReentrantLock();
void say(String msg) {
System.out.println(msg);
}
public void a() {
myReentrantLock.lock();
say("a");
b();
myReentrantLock.unlock();
}
public void b() {
myReentrantLock.lock();
say("b");
myReentrantLock.unlock();
}
}
可以看到,在调用a方法的时候,a方法里面有调用了b方法,但是此时已经加锁了,导致b永远不输出,那么怎么办呢?
在这里我们需要判断线程,当前线程应该是可以重新再进入,并且保证嵌套执行的,解决代码如下:
package com.asange.lock.reentrant;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* com.asange.lock.reentrant
* author:asange
* email:[email protected]
**/
public class MyReentrantLock implements Lock {
private boolean isLocked;
private int lockedCount;
private Thread lockedBy;
@Override
public synchronized void lock() {
while (isLocked && lockedBy != Thread.currentThread()) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isLocked = true;
lockedCount++;
lockedBy = Thread.currentThread();
}
@Override
public synchronized void unlock() {
if (lockedBy == Thread.currentThread()) {
lockedCount--;
if (lockedCount == 0) {
isLocked = false;
notify();
}
}
}
@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 Condition newCondition() {
return null;
}
}