目标:使用AQS实现简单的互斥锁
互斥锁实现:
- tryAcquire:尝试获取锁
- tryRelease:尝试释放锁
代码:
package com.miracle.study.syn;
import org.junit.jupiter.api.Test;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
/**
* @author Miracle
* @date 2021/4/13 19:59
*/
public class Mutex extends AbstractQueuedSynchronizer {
@Override
protected boolean tryAcquire(int arg) {
return compareAndSetState(0, 1);
}
@Override
protected boolean tryRelease(int arg) {
return compareAndSetState(1, 0);
}
public static int num = 0;
@Test
public void test() throws InterruptedException {
Mutex mutex = new Mutex();
for (int j = 0; j < 1000; j++){
new Thread(() -> {
mutex.tryAcquire(0);
num++;
mutex.tryRelease(0);
}).start();
}
Thread.sleep(1000);
System.out.println(num);
}
@Test
public void test1() throws InterruptedException {
Mutex mutex = new Mutex();
var t1 = new Thread(() -> {
mutex.tryAcquire(0);
for (int j = 0; j < 10000; j++) {
num++;
}
mutex.tryRelease(0);
});
var t2 = new Thread(() -> {
mutex.tryAcquire(0);
for (int j = 0; j < 10000; j++) {
num++;
}
mutex.tryRelease(0);
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(num);
}
}