5

java | 设计模式 同步模式 交替输出 wait & notify

 1 year ago
source link: https://benpaodewoniu.github.io/2022/12/20/java134/
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

这里的原理类似链表。

记录下一个的执行 flag,只有 flag 相同的时候,才会执行。

package com.redisc;

import lombok.extern.slf4j.Slf4j;

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

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

WaitNotify wn = new WaitNotify(1, 5);

new Thread(() -> {
wn.print("a", 1, 2);
}).start();
new Thread(() -> {
wn.print("b", 2, 3);
}).start();
new Thread(() -> {
wn.print("c", 3, 1);
}).start();
}

}

class WaitNotify {

private int flag;
private int loopNumber;

public WaitNotify(int flag, int loopNumber) {
this.flag = flag;
this.loopNumber = loopNumber;
}

public void print(String str, int waitFlag, int nextFlag) {
for (int i = 0; i < loopNumber; i++) {
synchronized (this) {
while (flag != waitFlag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(str);
flag = nextFlag;
this.notifyAll();
}
}
}
}
a
b
c
a
b
c
a
b
c
a
b
c
a
b
c

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK