Java多线程(6):锁与AQS(下)
您好,我是湘王,这是我的云海天,欢迎您来,欢迎您再来~
之前说过,AQS(抽象队列同步器)是Java锁机制的底层实现。既然它这么优秀,是骡子是马,就拉出来溜溜吧。
首先用重入锁来实现简单的累加,就像这样:
/** * 用重入锁实现累加 * * @author 湘王 */ public class MyLockTest { private final Lock lock = new ReentrantLock(); private int value; public int getNext() { lock.lock(); try { value++; } finally { lock.unlock(); } return value; } public static void main(String[] args) { MyLockTest myLock = new MyLockTest(); for (int i = 0; i < 5; i++) { new Thread(new Runnable() { @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(myLock.getNext()); } } }).start(); } } }