4

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

 1 year ago
source link: https://benpaodewoniu.github.io/2022/12/20/java132/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

wait & notify 版本。

先输出 2 再输出 1

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();

}

}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK