add demo for custom CLH
This commit is contained in:
parent
0faf89f006
commit
4843f5b4d2
@ -5,7 +5,6 @@ import java.util.concurrent.atomic.AtomicReference;
|
||||
/**
|
||||
* demo class for CLH. code from
|
||||
* <a href="https://mp.weixin.qq.com/s/jEx-4XhNGOFdCo4Nou5tqg">Java AQS 核心数据结构-CLH 锁</a>
|
||||
* This is only for demo, do not run the code this node class is not workable
|
||||
*/
|
||||
public class CLH {
|
||||
private final ThreadLocal<Node> node = ThreadLocal.withInitial(Node::new);
|
||||
@ -15,14 +14,14 @@ public class CLH {
|
||||
private volatile boolean locked;
|
||||
}
|
||||
|
||||
private void lock() {
|
||||
public void lock() {
|
||||
Node node = this.node.get();
|
||||
node.locked = true;
|
||||
Node pre = this.tail.getAndSet(node);
|
||||
while (!pre.locked) ;
|
||||
while (pre.locked) ;
|
||||
}
|
||||
|
||||
private void unlock() {
|
||||
public void unlock() {
|
||||
final Node node = this.node.get();
|
||||
node.locked = false;
|
||||
this.node.set(new Node());
|
||||
|
36
src/main/java/threaddemo/lock/CLHDemo.java
Normal file
36
src/main/java/threaddemo/lock/CLHDemo.java
Normal file
@ -0,0 +1,36 @@
|
||||
package threaddemo.lock;
|
||||
|
||||
public class CLHDemo {
|
||||
|
||||
public static void main(String[] args) throws InterruptedException {
|
||||
CLH clh = new CLH();
|
||||
Thread t1 = new Thread(() -> {
|
||||
System.out.println("t1 start");
|
||||
clh.lock();
|
||||
try {
|
||||
System.out.println("t1 get lock");
|
||||
Thread.sleep(1000L);
|
||||
System.out.println("t1 release lock");
|
||||
clh.unlock();
|
||||
System.out.println("t1 end");
|
||||
} catch (InterruptedException e) {
|
||||
throw new RuntimeException("interrupted");
|
||||
}
|
||||
});
|
||||
t1.start();
|
||||
Thread.sleep(10L);
|
||||
|
||||
Thread t2 = new Thread(() -> {
|
||||
System.out.println("t2 start");
|
||||
clh.lock();
|
||||
System.out.println("t2 get lock");
|
||||
clh.unlock();
|
||||
System.out.println("t2 release lock");
|
||||
System.out.println("t2 end");
|
||||
});
|
||||
t2.start();
|
||||
t1.join();
|
||||
t2.join();
|
||||
System.out.println("main end");
|
||||
}
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user