4

java | 设计模式 同步模式 交替输出 await & signal

 1 year ago
source link: https://benpaodewoniu.github.io/2022/12/20/java135/
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 | 设计模式 同步模式 交替输出 await & signal

使用 awaitsignal 来进行交替输出。

package com.redisc;

import lombok.extern.slf4j.Slf4j;

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

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

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

AwaitSignal awaitSignal = new AwaitSignal(5);
Condition a = awaitSignal.newCondition();
Condition b = awaitSignal.newCondition();
Condition c = awaitSignal.newCondition();

new Thread(() -> {
awaitSignal.print("a", a, b);
}).start();

new Thread(() -> {
awaitSignal.print("b", b, c);
}).start();

new Thread(() -> {
awaitSignal.print("c", c, a);
}).start();

// 主线程唤醒
Thread.sleep(1000);
awaitSignal.lock();
a.signal();
awaitSignal.unlock();
}

}

class AwaitSignal extends ReentrantLock {
private int loopNumber;

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

// 参数 1 打印内容 参数2 进入哪一间休息室 参数 3 下一间休息室
public void print(String str, Condition current, Condition next) {
for (int i = 0; i < loopNumber; i++) {
lock();
try {
current.await();
System.out.println(str);
next.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
unlock();
}
}
}
}

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK