Fair lock && Non-fair lock

Fair lock: after a thread has arrived, queue according to the FIFO;

Non-fair lock: after a thread comes, it fights for the lock directly, but it does not take the fair lock strategy.

Reentrant lock

The following code can run,

Lock lock = new ReentrantLock();
lock.lock();
lock.lock();
lock.unlock();
lock.unlock();
Copy the code

spinlocks

Public class Test1 {// AtomicReference<Thread> AtomicReference = new AtomicReference<>(); public void myLock() { Thread thread = Thread.currentThread(); System.out.println(thread.currentThread().getName() + "\t come in"); while (! atomicReference.compareAndSet(null, thread)) { } } public void myUnlock() { Thread thread = Thread.currentThread(); atomicReference.compareAndSet(thread, null); System.out.println(thread.currentThread().getName() + "\t invoked muUnlock"); } public static void main(String[] args) { Test1 test = new Test1(); new Thread(() -> { test.myLock(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } test.myUnlock(); }, "AA").start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } new Thread(() -> { test.myLock(); test.myUnlock(); }, "BB").start(); }}Copy the code

Read-write lock

ReentrantReadWriteLock

Read/write lock authentication:

public class ReadWriteTest { public static void main(String[] args) { MyCache myCache = new MyCache(); For (int I = 0; i < 5; i++) { new Thread(() -> { myCache.put(Strin, n); }, String.valueOf(i)).start(); } for (int I = 0; i < 5; i++) { final String n = String.valueOf(i); new Thread(() -> { myCache.get(n); }, String.valueOf(i)).start(); Class MyCache{private volatile Map<String, Object> Map = new HashMap<>(); Private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock(); public void put(String key, Object value) { rwLock.writeLock().lock(); Try {system.out.println (thread.currentThread ().getName() + "Thread starts writing "); map.put(key, value); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } system.out.println (thread.currentThread ().getName() + "Thread write completed "); }catch (Exception e){ e.printStackTrace(); }finally { rwLock.writeLock().unlock(); }} /** * Obtain cache * @param key */ public Object get(String key) {rwlock.readLock ().lock(); Try {system.out.println (thread.currentThread ().getName() + "Thread begins to read "); Object result = map.get(key); Try {thread.sleep (300); } catch (InterruptedException e) { e.printStackTrace(); } system.out.println (thread.currentThread ().getName() + "Thread read complete" + result); return result; }catch (Exception e){ e.printStackTrace(); return null; }finally { rwLock.readLock().unlock(); }}}Copy the code