1 //自定义的自旋锁
2 public class SpinLockDemo {
3 public static void main(String[] args) {
4
5 }
6
7
8 AtomicReference reference = new AtomicReference<Thread>();
9
10 public void spinlock(){
11
12 }
13
14 //加锁
15 public void lock(){
16 Thread thread = Thread.currentThread();
17
18
19
20 //自旋锁
21 while (!reference.compareAndSet(null,thread)) {
22 System.out.println(Thread.currentThread().getName() + " 开始自旋...");
23 try {
24 Thread.sleep(400);
25 } catch (InterruptedException e) {
26 e.printStackTrace();
27 }
28 }
29
30 System.out.println(Thread.currentThread().getName() +" lock");
31
32 }
33
34
35 //解锁
36 public void unlock(){
37 Thread thread = Thread.currentThread();
38
39 System.out.println(Thread.currentThread().getName() +" unlock");
40
41
42 reference.compareAndSet(thread,null);
43 }
44 }
45
46 class LockTest{
47
48
49
50 public static void main(String[] args) {
51
52 SpinLockDemo lock = new SpinLockDemo();
53
54 new Thread(()->{
55 lock.lock();
56 try {
57 TimeUnit.SECONDS.sleep(3);
58 } catch (Exception e) {
59 e.printStackTrace();
60 } finally {
61 lock.unlock();
62 }
63 },"Thread-01").start();
64
65 try {
66 TimeUnit.SECONDS.sleep(1);
67 } catch (InterruptedException e) {
68 e.printStackTrace();
69 }
70
71 new Thread(()->{
72
73 lock.lock();
74
75 try {
76 TimeUnit.SECONDS.sleep(1);
77 } catch (Exception e) {
78 e.printStackTrace();
79 } finally {
80 lock.unlock();
81 }
82 },"Thread-02").start();
83 }
84 }