/ **
不可重入锁
*/
public class BadSpinLock {
AtomicReference<Thread> owner = new AtomicReference<Thread>();//持有自旋锁的线程对象public void lock() {
Thread cur = Thread.currentThread();
while (!owner.compareAndSet(null, cur)) { // 如果当前期望不成功,自旋
System.out.println(cur.getName()+ " wait lock release");
}
}
public void unLock() {
Thread cur = Thread.currentThread();
if (cur == owner.get()) {
owner.compareAndSet(cur, null);
System.out.println(cur.getName()+ " release lock");
}
}
}
/ **
重入锁
*/
public class SpinLock {
AtomicReference<Thread> owner = new AtomicReference<Thread>();//持有自旋锁的线程对象
private int count;
public void lock(){
Thread cur = Thread.currentThread();
if (cur == owner.get()){
count++;
return;
}
while (!owner.compareAndSet(null, cur)){
}
}
public void unLock(){
Thread cur = Thread.currentThread();
if (cur == owner.get()){
if (count > 0){
count--;
}else{
owner.compareAndSet(cur, null);
}
}
}
}
package lock;
public class Test implements Runnable {
static int sum;
private SpinLock lock;
public Test(SpinLock lock) {
this.lock = lock;
}
/**
* @param args
* @throws InterruptedException
*/
@SuppressWarnings("static-access")
public static void main(String[] args) throws InterruptedException {
SpinLock lock = new SpinLock();
for (int i = 0; i < 100; i++) {
Test test = new Test(lock);
Thread t = new Thread(test);
t.start();
}
Thread.currentThread().sleep(1000);
System.out.println(sum);
}
@Override
public void run() {
this.lock.lock();
this.lock.lock();
sum++;
this.lock.unLock();
this.lock.unLock();
}
}