1.简单实现
实现Lock接口并实现其lock方法与unlock方法
//利用Lock接口实现一个可重入锁
public class ReLock implements Lock{
private boolean isLock = false; //锁是否被获取
private int count = 0; //记录一个线程获取同一个锁的次数
private Thread lockBy = null; //记录当前获取到锁的线程
//获取锁
@Override
public synchronized void lock() {
Thread currentThread = Thread.currentThread();
while(isLock && currentThread!=lockBy){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isLock = true;
lockBy = currentThread;
count++;
}
//释放锁
@Override
public synchronized void unlock() {
count--;
if(count == 0) {
isLock = false;
notify();
}
}
//实现其他方法
}
2.测试
public class ReLockTest {
//创建自定义的可重入锁对象
public ReLock lock = new ReLock();
public int value = 0;
public void getNext(){ //自定义锁测试方法
//获取锁
lock.lock();
value++;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(value);
//释放锁
lock.unlock();
}
public void ReLockA(){ //可重入测试方法
//获取锁
lock.lock();
value++;
ReLockB(); //可重入则正常运行
System.out.println("A: "+value);
//释放锁
lock.unlock();
}
public void ReLockB(){
//获取锁
lock.lock();
value++;
System.out.println("B: "+value);
//释放锁
lock.unlock();
}
@Test
public void test(){
ReLockTest test = new ReLockTest();
new Thread(new Runnable() { //自定义锁测试线程1
@Override
public void run() {
while(true){
test.getNext();
//test.ReLockA(); //可重入测试
}
}
}).start();
new Thread(new Runnable() { //自定义锁测试线程2
@Override
public void run() {
while(true){
test.getNext();
}
}
}).start();
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}