Skip to content

Instantly share code, notes, and snippets.

@jingjiecb
Created April 7, 2023 14:44
Show Gist options
  • Save jingjiecb/902b8dd310234584aaef700e835394e6 to your computer and use it in GitHub Desktop.
Save jingjiecb/902b8dd310234584aaef700e835394e6 to your computer and use it in GitHub Desktop.
自己继承AQS实现自定义锁,交替输入输出0和1
package org.example;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author claws
* @since 2023/4/7
*/
public class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
OneByOneLock oneByOneLock = new OneByOneLock(0);
Runnable task1 = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; ++i) {
oneByOneLock.acquire(1);
System.out.println(1);
oneByOneLock.release(0);
}
}
};
Runnable task2 = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
oneByOneLock.acquire(0);
System.out.println(0);
oneByOneLock.release(1);
}
}
};
new Thread(task1).start();
new Thread(task2).start();
}
}
class OneByOneLock extends AbstractQueuedSynchronizer {
public OneByOneLock(int initNum) {
setState(initNum);
}
@Override
protected boolean tryAcquire(int outputNum) {
if (getState() == outputNum) {
setExclusiveOwnerThread(Thread.currentThread());
return true;
}
return false;
}
@Override
protected boolean tryRelease(int nextNum) {
setState(nextNum);
setExclusiveOwnerThread(null);
return true;
}
@Override
protected boolean isHeldExclusively() {
return getExclusiveOwnerThread() == Thread.currentThread();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment