[Java] 纯文本查看 复制代码
class spinlock {
private AtomicReference<Thread> cas;
spinlock(AtomicReference<Thread> cas){
this.cas = cas;
}
public void lock() {
Thread current = Thread.currentThread();
// 利用CAS
while (!cas.compareAndSet(null, current)) { //为什么预期是null??
// DO nothing
System.out.println("I am spinning");
}
}
public void unlock() {
Thread current = Thread.currentThread();
cas.compareAndSet(current, null);
}
}
[Java] 纯文本查看 复制代码
package ddx.多线程;
import java.util.concurrent.atomic.AtomicReference;
public class 自旋锁 {
public static void main(String[] args) {
AtomicReference<Thread> cas = new AtomicReference<Thread>();
Thread thread1 = new Thread(new Task(cas));
Thread thread2 = new Thread(new Task(cas));
thread1.start();
thread2.start();
}
}
//自旋锁验证
class Task implements Runnable {
private AtomicReference<Thread> cas;
private spinlock slock ;
public Task(AtomicReference<Thread> cas) {
this.cas = cas;
this.slock = new spinlock(cas);
}
@Override
public void run() {
slock.lock(); //上锁
for (int i = 0; i < 10; i++) {
//Thread.yield();
System.out.println(i);
}
slock.unlock();
}
}