0%

java | 设计模式 同步模式 交替输出 park & unpark

park & unpark 的交替输出。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package com.redisc;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.LockSupport;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j(topic = "c.Run")
public class Run {

static Thread t1;
static Thread t2;
static Thread t3;

public static void main(String[] args) throws Exception {
ParkUnpark pu = new ParkUnpark(5);
t1 = new Thread(() -> {
pu.print("a", t2);
});
t2 = new Thread(() -> {
pu.print("b", t3);
});
t3 = new Thread(() -> {
pu.print("c", t1);
});

t1.start();
t2.start();
t3.start();

LockSupport.unpark(t1);
}

}

class ParkUnpark {
private int loopNumber;

public ParkUnpark(int loopNumber) {
this.loopNumber = loopNumber;
}

// 参数 1 打印内容 参数2 进入哪一间休息室 参数 3 下一间休息室
public void print(String str, Thread next) {
for (int i = 0; i < loopNumber; i++) {
LockSupport.park();
System.out.println(str);
LockSupport.unpark(next);
}
}
}
请我喝杯咖啡吧~