java自旋锁

此文章不涉及与互斥锁等比比较,只是单纯的介绍一个自旋锁,如果想要了解更多可以点击参考链接

一个自旋锁例子

自旋锁的介绍原理等过程我就不在此介绍了,下面的参考已经写的非常不错了!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/***
* 自旋锁
* @author Joker
*
*/
public class SpinLock {
AtomicReference<Thread> owner = new AtomicReference<Thread>();
private int count ;
public void lock() {
Thread currentThread = Thread.currentThread();
System.out.println("lock() -> " + currentThread.getName());
if (currentThread == owner.get()) {
count++; // 获取锁的次数
return ;
}
// 当线程越来越多由于while循环会浪费cpu时间片,compareAndSet需要多次对同一内存进行访问
while (!owner.compareAndSet(null, currentThread)) {
}
}
public void unLock() {
Thread currentThread = Thread.currentThread();
System.out.println("unLock() -> " + currentThread.getName());
if (currentThread == owner.get()) {
if (count > 0) {
count--;
} else {
owner.compareAndSet(currentThread, null);
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class SpinLockTest implements Runnable{
static int sum ;
private SpinLock lock;
public SpinLockTest(SpinLock lock) {
this.lock = lock;
}
public void run() {
this.lock.lock();
this.lock.lock();
System.out.println("当前线程 " + Thread.currentThread().getName() + " start...");
sum++;
System.out.println("当前线程 " + Thread.currentThread().getName() + " end...");
this.lock.unLock();
this.lock.unLock();
}
public static void main(String[] args) throws InterruptedException {
SpinLock lock = new SpinLock();
for (int i = 1; i < 5; i++) {
SpinLockTest lockTest = new SpinLockTest(lock);
Thread t = new Thread(lockTest, "thread-lock-"+i);
t.start();
}
Thread.sleep(1000);
System.out.println(sum);
}
}

最后附上一张我自己画的一张运行图

java自旋锁

参考

http://www.cnblogs.com/cposture/p/SpinLock.html#_label0

人生苦短,我要打赏!