|
| 1 | +package com.segmentfault.deep.in.java.aqs; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.util.ArrayList; |
| 5 | +import java.util.List; |
| 6 | +import java.util.concurrent.ExecutorService; |
| 7 | +import java.util.concurrent.Executors; |
| 8 | +import java.util.concurrent.TimeUnit; |
| 9 | +import java.util.concurrent.locks.Condition; |
| 10 | +import java.util.concurrent.locks.Lock; |
| 11 | +import java.util.concurrent.locks.ReentrantLock; |
| 12 | + |
| 13 | +public class AbstractQueuedSynchronizerDemo { |
| 14 | + |
| 15 | + // ReentrantLock is AbstractQueuedSynchronizer |
| 16 | + private static Lock lock = new ReentrantLock(); |
| 17 | + |
| 18 | + // Condition is a part of ReentrantLock or AbstractQueuedSynchronizer |
| 19 | + private static Condition condition = lock.newCondition(); |
| 20 | + |
| 21 | + public static void main(String[] args) throws InterruptedException { |
| 22 | + |
| 23 | + ExecutorService executorService = Executors.newFixedThreadPool(3); |
| 24 | + |
| 25 | + // 一个线程获得锁,另外一个线程入队 |
| 26 | + |
| 27 | + // main -> thread-2.interrupt() |
| 28 | + // sub-threads |
| 29 | + List<Thread> threads = new ArrayList<>(); |
| 30 | + |
| 31 | + executorService.submit(() -> { |
| 32 | + threads.add(Thread.currentThread()); |
| 33 | + action(); |
| 34 | + |
| 35 | + }); // thread-1 |
| 36 | + executorService.submit(AbstractQueuedSynchronizerDemo::action); // thread-1 |
| 37 | + executorService.submit(AbstractQueuedSynchronizerDemo::action); // thread-2 |
| 38 | + executorService.submit(AbstractQueuedSynchronizerDemo::action); // thread-3 |
| 39 | + |
| 40 | + |
| 41 | + // 非公平锁 |
| 42 | + // thread-1 unlock -> release -> unpark thread-2 -> thread-2 try acquire |
| 43 | + // thread-4 or thread-5 lock -> try acquire |
| 44 | + |
| 45 | + // PS : unpark = LockSupport.unpark |
| 46 | + |
| 47 | + // 公平锁 |
| 48 | + // thread-1 unlock -> release -> unpark thread-2 -> thread-2 try acquire |
| 49 | + // thread-2 lock -> .. |
| 50 | + // thread-3 wait |
| 51 | + // thread-4 wait |
| 52 | + // thread-5 wait |
| 53 | + |
| 54 | + // 等待 200 秒 |
| 55 | + executorService.awaitTermination(200, TimeUnit.SECONDS); |
| 56 | + // 关闭线程池 |
| 57 | + executorService.shutdown(); |
| 58 | + |
| 59 | + } |
| 60 | + |
| 61 | + private static void action() { |
| 62 | + System.out.printf("当前线程[%s] 正在等待您的输入\n", Thread.currentThread().getName()); |
| 63 | + // I/O 中断线程 |
| 64 | + try { |
| 65 | + |
| 66 | + |
| 67 | + // 利用 ReentrantLock 作为 AQS 实现,理解内部数据结构 |
| 68 | + lock.lock(); |
| 69 | + System.in.read(); |
| 70 | + System.out.printf("当前线程[%s] 执行结束...\n", Thread.currentThread().getName()); |
| 71 | + } catch (IOException e) { |
| 72 | + throw new RuntimeException(); |
| 73 | + } finally { |
| 74 | + lock.unlock(); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | +} |
0 commit comments