共计 1008 个字符,预计需要花费 3 分钟才能阅读完成。
1. 自旋锁成品代码如下:
package lock.spinlock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* @author wuyiccc
* @date 2020/7/19 10:37
* 岂曰无衣,与子同袍~
*/
public class SpinLock {private AtomicReference<Thread> sign = new AtomicReference<>();
public void lock() {Thread current = Thread.currentThread();
while (!sign.compareAndSet(null, current)) {System.out.println("获取自旋锁失败,再次尝试");
}
}
public void unlock() {Thread current = Thread.currentThread();
sign.compareAndSet(current, null);
}
public static void main(String[] args) {SpinLock lock = new SpinLock();
Runnable runnable = new Runnable() {
@Override
public void run() {System.out.println(Thread.currentThread().getName() + "开始尝试获取自旋锁...");
lock.lock();
System.out.println(Thread.currentThread().getName() + "获取自旋锁胜利...");
try {TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {e.printStackTrace();
} finally {System.out.println(Thread.currentThread().getName() + "开释了自旋锁...");
lock.unlock();}
}
};
Thread t1 = new Thread(runnable, "线程 1");
Thread t2 = new Thread(runnable, "线程 2");
t1.start();
t2.start();}
}
2. 外围代码解说
正文完