1.可重入锁
解读:锁作为并发共享数据保证一致性的工具,大多数内置锁是可重入的
利用计数器
代码:
package cn.zwl.other;
/**
*
* 可重入锁
* @author dell
*
*/
public class LocaTest {
public void test() {
synchronized (this) {
while(true) {
synchronized (this) {
System.out.println("ReentrantLock1");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
new LocaTest().test();
}
}
package cn.zwl.other;
/**
*
* 可重入锁
* @author dell
*
*/
public class LocaTest3 {
ReLock lock=new ReLock();
public void a() {
lock.lock();
System.out.println(lock.getHoldCount());
doSomething();
lock.unlock();
System.out.println(lock.getHoldCount());
}
public void doSomething() {
lock.lock();
System.out.println(lock.getHoldCount());
System.out.println("我要干坏事了,嘿嘿");
lock.unlock();
System.out.println(lock.getHoldCount());
}
public static void main(String[] args) throws Exception {
LocaTest3 lc2=new LocaTest3();
lc2.a();
lc2.doSomething();
Thread.sleep(1000);
System.out.println(lc2.lock.getHoldCount());
}
}
class ReLock{
//是否占用
private boolean isLocked=false;
//使用锁
private Thread lockedBy=null;//存储线程
private int holdCount=0;//计数器
public synchronized void lock() {
Thread t=Thread.currentThread();
while(isLocked&&lockedBy!=t) {
try {
wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
isLocked =true;
lockedBy=t;
holdCount++;
}
//释放锁
public synchronized void unlock() {
if (Thread.currentThread()==lockedBy) {
holdCount--;
if(holdCount==0) {
isLocked=false;
notifyAll();
lockedBy=null;
}
}
}
public int getHoldCount() {
return holdCount;
}
}
package cn.zwl.other;
/**
*
* 自带可重入锁
* @author dell
*
*/
import java.util.concurrent.locks.ReentrantLock;
public class LocaTest4 {
ReentrantLock lock=new ReentrantLock ();
public void a() {
lock.lock();
System.out.println(lock.getHoldCount());
doSomething();
lock.unlock();
System.out.println(lock.getHoldCount());
}
public void doSomething() {
lock.lock();
System.out.println(lock.getHoldCount());
System.out.println("我要干坏事了,嘿嘿");
lock.unlock();
System.out.println(lock.getHoldCount());
}
public static void main(String[] args) throws Exception {
LocaTest4 lc2=new LocaTest4();
lc2.a();
lc2.doSomething();
Thread.sleep(1000);
System.out.println(lc2.lock.getHoldCount());
}
}