-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMySpinLock.java
More file actions
50 lines (46 loc) · 1.7 KB
/
MySpinLock.java
File metadata and controls
50 lines (46 loc) · 1.7 KB
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
40
41
42
43
44
45
46
47
48
49
50
package com.xycode.spinlock;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
/**
* ClassName: MySpinLock
*
* @Author: xycode
* @Date: 2019/10/28
**/
public class MySpinLock {
private AtomicReference<Thread> atomicReference=new AtomicReference<>(null);
public void lock(){//实现自旋锁,CPU占用较高
Thread thread=Thread.currentThread();
while(!atomicReference.compareAndSet(null,thread)){
// System.err.println("Thread-"+thread.getId()+" fail to acquire lock");
thread.yield();//让出CPU,减少锁竞争,不过不保证一定有效...
}
}
public void unlock(){
Thread thread=Thread.currentThread();
atomicReference.compareAndSet(thread,null);
}
public static void main(String[] args) {
Thread[] t=new Thread[5];
MySpinLock spinLock=new MySpinLock();
for(int i=0;i<t.length;++i){
t[i]=new Thread(()->{
try {
spinLock.lock();
System.out.println("Thread-"+Thread.currentThread().getId()+" acquire lock");
System.out.println("Thread-"+Thread.currentThread().getId()+" working...");
try {
TimeUnit.SECONDS.sleep(2);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Thread-"+Thread.currentThread().getId()+" release lock");
System.out.println();
}finally {
spinLock.unlock();
}
});
}
for(Thread thread:t) thread.start();
}
}