利用CAS实现自旋锁
1.自旋锁概念2.编写自旋锁3.测试自旋锁
1.自旋锁概念
自旋锁(spinlock):是指当一个线程在获取锁的时候,如果锁已经被其它线程获取,那么该线程将循环等待,然后不断的判断锁是否能够被成功获取,直到获取到锁才会退出循环。
2.编写自旋锁
import java
.util
.concurrent
.atomic
.AtomicBoolean
;
public class SpinLock {
private AtomicBoolean cas
= new AtomicBoolean(false);
private Thread spinLockOwnerThread
= null
;
public void lock(){
while (!cas
.compareAndSet(false,true))
{
}
spinLockOwnerThread
= Thread
.currentThread();
}
public void unLock(){
if (Thread
.currentThread()==spinLockOwnerThread
)
{
spinLockOwnerThread
= null
;
cas
.set(false);
}
}
}
3.测试自旋锁
class Test {
private static final SpinLock spinLock
= new SpinLock();
public static void main(String
[] args
) {
Thread t1
= new Thread(Test
::run
,"t1");
Thread t2
= new Thread(Test
::run
,"t2");
Thread t3
= new Thread(Test
::run
,"t3");
Thread t4
= new Thread(Test
::run
,"t4");
t1
.start();
t2
.start();
t3
.start();
t4
.start();
}
public static void run(){
spinLock
.lock();
System
.out
.println(Thread
.currentThread().getName());
try
{
Thread
.sleep(5000);
}
catch (InterruptedException e
)
{
e
.printStackTrace();
}
finally
{
spinLock
.unLock();
}
}
}