ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
### 自定义同步工具 了解AQS基本原理以后,按照上面所说的AQS知识点,自己实现一个同步工具。 ~~~ public class LeeLock { private static class Sync extends AbstractQueuedSynchronizer { @Override protected boolean tryAcquire (int arg) { return compareAndSetState(0, 1); } @Override protected boolean tryRelease (int arg) { setState(0); return true; } @Override protected boolean isHeldExclusively () { return getState() == 1; } } private Sync sync = new Sync(); public void lock () { sync.acquire(1); } public void unlock () { sync.release(1); } } ~~~ 通过我们自己定义的Lock完成一定的同步功能。 ~~~ public class LeeMain { static int count = 0; static LeeLock leeLock = new LeeLock(); public static void main (String[] args) throws InterruptedException { Runnable runnable = new Runnable() { @Override public void run () { try { leeLock.lock(); for (int i = 0; i < 10000; i++) { count++; } } catch (Exception e) { e.printStackTrace(); } finally { leeLock.unlock(); } } }; Thread thread1 = new Thread(runnable); Thread thread2 = new Thread(runnable); thread1.start(); thread2.start(); thread1.join(); thread2.join(); System.out.println(count); } } ~~~ 上述代码每次运行结果都会是20000。通过简单的几行代码就能实现同步功能,这就是AQS的强大之处