手动实现一个可重入锁

Posted 凌晨六点半

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了手动实现一个可重入锁相关的知识,希望对你有一定的参考价值。

package com.roocon.thread.ta1;

public class Sequence {

    private MyLock lock = new MyLock();

    private int value;

    public int getNext() {
        lock.lock();
        value++;
        lock.unlock();
        return value;

    }

    public static void main(String[] args) {

        Sequence s = new Sequence();

        new Thread(new Runnable() {

            @Override
            public void run() {
                while(true)
                    System.out.println(s.getNext());
            }
        }).start();
        new Thread(new Runnable() {

            @Override
            public void run() {
                while(true)
                    System.out.println(s.getNext());
            }
        }).start();
        new Thread(new Runnable() {

            @Override
            public void run() {
                while(true)
                    System.out.println(s.getNext());
            }
        }).start();
        new Thread(new Runnable() {

            @Override
            public void run() {
                while(true)
                    System.out.println(s.getNext());
            }
        }).start();
        new Thread(new Runnable() {

            @Override
            public void run() {
                while(true)
                    System.out.println(s.getNext());
            }
        }).start();
    }

}

 

package com.roocon.thread.ta1;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

public class MyLock implements Lock {

private boolean isLocked = false;

@Override
public synchronized void lock() {
/*
if (isLocked == false) {//第一个进来的线程不需要等待
isLocked = true;
}else {//其他线程需要等待
try {
wait();//使用wait模拟等待
} catch (InterruptedException e) {
e.printStackTrace();
}
}
*/
if (isLocked) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
isLocked = true;

}

@Override
public synchronized void unlock() {
isLocked = false;
notify();//wait notify 必须和synchronized一起使用
}


@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;
}
}

 

运行结果:

1
2
3
4
5
6
7
...

 

以上是关于手动实现一个可重入锁的主要内容,如果未能解决你的问题,请参考以下文章

6.23Java多线程可重入锁实现原理

可重入锁的实现

可重入锁和不可重入锁

可重入锁和不可重入锁

可重入锁的实现

ReentrantLock可重入锁原理