java锁的种类以及辨析(一):自旋锁

[/code]Java的多线程安全是基于Lock机制(或者隐式锁synchronized)实现的,而Lock的性能往往不如人意。
原因是,monitorenter与monitorexit这两个控制多线程同步的bytecode原语,是JVM依赖操作系统互斥(mutex)来实现的。
互斥是一种会导致线程挂起,并在较短的时间内又需要重新调度回原线程的,较为消耗资源的操作。

为了优化Java的Lock机制,从Java6开始引入了轻量级锁的概念。

轻量级锁(Lightweight Locking)本意是为了减少多线程进入互斥的几率,并不是要替代互斥。
它利用了CPU原语Compare-And-Swap(CAS,汇编指令CMPXCHG),尝试在进入互斥前,进行补救。

这里先介绍第一种轻量级锁 自旋锁

自旋锁的原理是 让其他线程不断的循环等待着去用自身线程引用去加锁(当锁的竞争不大且,锁的时间段比较长的时候适用)

使用 AtomicReference 的方法 compareAndSet(V expect, V update):如果当前值 == 预期值,则以原子方式将该值设置为给定的更新值。

代码如下:
[code="java"]
class SpinLock {

private AtomicReference<Thread> sign = new AtomicReference<Thread>();

public void lock() {
Thread current = Thread.currentThread();
//System.out.println(Thread.currentThread().getName() + " wait");
while (!sign.compareAndSet(null, current)) {

}
}

public void unlock() {
Thread current = Thread.currentThread();
sign.compareAndSet(current, null);
}
}


实例如下:


package thread;

import java.util.concurrent.atomic.AtomicReference;

public class SpinLockTest {
private static int count = 0;
private static SpinLock spinLock = new SpinLock();
/**
* @param args
*/
@SuppressWarnings("static-access")
public static void main(String[] args) {

for (int i = 0; i < 100000; i++) {
Thread thread = new Thread(new Runnable(){
@Override
public void run() {
spinLock.lock();
count++;
spinLock.unlock();
}
});
thread.start();
}
System.out.println("here");
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(count);
}
}
/**
* 自旋锁 让其他线程不断的循环等待着去用自身线程引用去加锁(当锁的竞争不大且,锁的时间段比较长的时候适用)。
*/
class SpinLock {

private AtomicReference<Thread> sign = new AtomicReference<Thread>();

public void lock() {
Thread current = Thread.currentThread();
//System.out.println(Thread.currentThread().getName() + " wait");
while (!sign.compareAndSet(null, current)) {

}
}

public void unlock() {
Thread current = Thread.currentThread();
sign.compareAndSet(current, null);
}
}


稍微面向对象点 是这样子的

package thread;

import java.util.concurrent.atomic.AtomicReference;

public class SpinLockTest2 {

static int count = 100;

public static void main(String[] args) {
final SplinLock lock = new SplinLock();
for(int i=0;i<100;i++){
new Thread(new ThreadDemo(lock)).start();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(count);
}
}

class ThreadDemo implements Runnable{
private SplinLock lock;
public ThreadDemo(SplinLock lock){
this.lock = lock;
}
@Override
public void run() {
lock.lock();
System.out.println(Thread.currentThread().getName()+"---"+SpinLockTest2.count);
SpinLockTest2.count--;
lock.unlock();
}
}


class SplinLock{

private AtomicReference<Thread> reference = new AtomicReference<Thread>();

public void lock(){
Thread thread = Thread.currentThread();
while(!reference.compareAndSet(null, thread)){

}
}

public void unlock(){
Thread thread = Thread.currentThread();
reference.compareAndSet(thread, null);
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

annan211

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值