可重入锁: 锁可以连续使用
计数器 + 判断进入的线程是不是已经锁定的线程, 如果是那就不用等待, 直接使用
- public class my {
- public static void main(String[]args)
- {
- my m=new my();
- m.test();
- }
- public void test()
- {
- synchronized(this)// 第一次获得锁
- {
- while(true)
- {
- synchronized(this)// 第二次获得锁, 假如没有可重入锁, 将会造成死锁
- {
- System.out.println("relock");
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- }
手工实现:
- public class my {
- Lock lock=new Lock();
- public void a() throws InterruptedException
- {
- lock.lock();
- System.out.println(lock.getCount());
- b();
- lock.unlock();
- System.out.println(lock.getCount());
- }
- public void b() throws InterruptedException
- {
- lock.lock();
- System.out.println(lock.getCount());
- //..
- lock.unlock();
- System.out.println(lock.getCount());
- }
- public static void main(String[]args) throws InterruptedException
- {
- my m=new my();
- m.a();
- Thread.sleep(1000);
- System.out.println(m.lock.getCount());
- }
- }
- class Lock{
- // 是否占用
- private boolean isLocked=false;
- private Thread lockedBy=null;// 存储线程, 如果是自身就不等了
- private int count=0;
- // 使用锁
- public synchronized void lock() throws InterruptedException
- {
- Thread t=Thread.currentThread();
- while(isLocked&&lockedBy!=t)// 如果被锁住了, 且不是当前线程
- {
- wait();
- }
- isLocked=true;
- lockedBy=t;
- count++;
- }
- // 释放锁
- public synchronized void unlock()
- {
- if(Thread.currentThread()==lockedBy)
- {
- count--;
- if(count==0)
- {
- isLocked=false;
- notify();
- lockedBy=null;
- }
- }
- isLocked=false;
- notify();
- }
- public int getCount() {
- return count;
- }
- public void setCount(int count) {
- this.count = count;
- }
- }
来源: http://www.bubuko.com/infodetail-3161530.html