|
| 1 | +import java.util.concurrent.*; |
| 2 | + |
| 3 | +/** |
| 4 | + * @Author: zzStar |
| 5 | + * @Date: 2021/9/9 |
| 6 | + * @Description: 交叉打印ABC,Semaphore |
| 7 | + */ |
| 8 | +public class printABCExample03 { |
| 9 | + |
| 10 | + private int times = 10; |
| 11 | + |
| 12 | + // 只有A 初始信号量为1,第一次获取到的只能是A |
| 13 | + private static Semaphore A = new Semaphore(1); |
| 14 | + |
| 15 | + private static Semaphore B = new Semaphore(0); |
| 16 | + |
| 17 | + private static Semaphore C = new Semaphore(0); |
| 18 | + |
| 19 | + public static void main(String[] args) { |
| 20 | + |
| 21 | + ExecutorService executorService = new ThreadPoolExecutor( |
| 22 | + 3, |
| 23 | + 5, |
| 24 | + 3, |
| 25 | + TimeUnit.SECONDS, |
| 26 | + new LinkedBlockingDeque<>(3), |
| 27 | + Executors.defaultThreadFactory(), |
| 28 | + new ThreadPoolExecutor.DiscardOldestPolicy()); |
| 29 | + |
| 30 | + printABCExample03 printAbc = new printABCExample03(); |
| 31 | + executorService.execute(() -> printAbc.print("A", A, B)); |
| 32 | + executorService.execute(() -> printAbc.print("B", B, C)); |
| 33 | + executorService.execute(() -> printAbc.print("C", C, A)); |
| 34 | + |
| 35 | + |
| 36 | + executorService.shutdown(); |
| 37 | + } |
| 38 | + |
| 39 | + private void print(String name, Semaphore current, Semaphore next) { |
| 40 | + for (int i = 0; i < times; i++) { |
| 41 | + try { |
| 42 | + current.acquire(); |
| 43 | + System.out.println(name); |
| 44 | + next.release(); |
| 45 | + } catch (InterruptedException e) { |
| 46 | + e.printStackTrace(); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | +} |
0 commit comments