-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpinLockDemo.java
More file actions
48 lines (43 loc) · 1.39 KB
/
SpinLockDemo.java
File metadata and controls
48 lines (43 loc) · 1.39 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
package edu.nwpu.zhao.Test;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
public class SpinLockDemo {
AtomicReference<Thread> atomicReference = new AtomicReference();
public void mylock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"\t come in");
while(!atomicReference.compareAndSet(null,thread)){
}
}
public void myunlock(){
Thread thread = Thread.currentThread();
System.out.println(thread.getName()+"\t come out");
atomicReference.compareAndSet(thread,null);
}
public static void main(String[] args){
SpinLockDemo spinLockDemo = new SpinLockDemo();
new Thread(()->{
spinLockDemo.mylock();
try{
TimeUnit.SECONDS.sleep(5);
}catch (InterruptedException e){
e.printStackTrace();
}
spinLockDemo.myunlock();
},"AA").start();
try{
TimeUnit.SECONDS.sleep(1);
}catch (InterruptedException e){
e.printStackTrace();
}
new Thread(()->{
spinLockDemo.mylock();
try{
TimeUnit.SECONDS.sleep(1);
}catch (InterruptedException e){
e.printStackTrace();
}
spinLockDemo.myunlock();
},"BB").start();
}
}