1.編寫自旋鎖
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)
{
cas.set(false);
spinLockOwnerThread = null;
}
}
}
2.測試自旋鎖
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();
}
}
}