package cn.edu.sdk;
import sun.misc.Unsafe;
import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.LockSupport;
public class MyAQS {
private volatile int state = 0;
private Thread threadHolder;
private ConcurrentLinkedQueue<Thread> waiters = new ConcurrentLinkedQueue<>();
private static Unsafe unsafe;
static {
try {
unsafe = MyAQS.getUnsafeInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
public static Unsafe getUnsafeInstance() throws Exception {
Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafeInstance.setAccessible(true);
return (Unsafe) theUnsafeInstance.get(Unsafe.class);
}
public int getState() {
return state;
}
public void setState(int state) {
state = state;
}
public Thread getThreadHolder() {
return threadHolder;
}
public void setThreadHolder(Thread threadHolder) {
this.threadHolder = threadHolder;
}
public boolean acquire() throws Exception {
int c = getState();
if (c == 0){
long offset = unsafe.objectFieldOffset(MyAQS.class.getDeclaredField("state"));
Thread thread = Thread.currentThread();
if ( (waiters.size() == 0 || thread == waiters.peek())&& unsafe.compareAndSwapInt(state, offset, 0 , 1)){
threadHolder = thread;
return true;
}
}
return false;
}
public void lock() throws Exception {
if (acquire()){
return;
}
Thread c = Thread.currentThread();
waiters.add(c);
for(;;){
if ((c == waiters.peek() ) && acquire()){
waiters.poll();
break;
}
LockSupport.park();
}
}
public void unLock() throws Exception {
if (threadHolder != Thread.currentThread()){
throw new RuntimeException(" 不是持有锁的线程不能枷锁 ");
}
long offset = unsafe.objectFieldOffset(MyAQS.class.getDeclaredField("state"));
boolean isUnLock = unsafe.compareAndSwapInt(state, offset, 1, 0);
if (isUnLock){
setThreadHolder(null);
Thread first = waiters.peek();
if (first != null){
LockSupport.unpark(first);
}
}
}
}
package cn.edu.sdk;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
public class TestThread {
public static void main(String[] args) {
Order order = new Order();
AtomicInteger integer = new AtomicInteger(0);
for (int i = 0; i < 50; i++) {
new Thread(() ->{
for (int j = 0; j < 20; j++) {
order.descOrder();
integer.getAndIncrement();
}
}, String.valueOf(i)).start();
}
while (Thread.activeCount() > 2){
Thread.yield();
}
System.out.println(integer);
}
}
class Order{
private int orders = 10;
private MyAQS myAQS = new MyAQS();
public void descOrder() {
try {
myAQS.lock();
if (orders > 0){
TimeUnit.MILLISECONDS.sleep(200);
System.out.println("线程" + Thread.currentThread().getName() + "---->获取订单" + orders --);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
myAQS.unLock();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}