5

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

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

park & unpark 的交替输出。

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

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK