0%

java | 设计模式 同步模式 顺序控制 wait & notify

wait & notify 版本。

先输出 2 再输出 1

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
package com.redisc;

import lombok.extern.slf4j.Slf4j;

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

static final Object lock = new Object();
// 表示 t2 是否运行过
static boolean t2runned = false;

public static void main(String[] args) throws Exception {

Thread t1 = new Thread(() -> {
synchronized (lock) {
while (!t2runned) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
log.debug("1");
}
}, "t1");

Thread t2 = new Thread(() -> {
synchronized (lock) {
log.debug("2");
t2runned = true;
lock.notify();
}
}, "t2");

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

}

}
请我喝杯咖啡吧~