闲来无事,练习一下,主要用重入锁的 condition 解决了 notify 的效率问题
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
public static ReentrantLock reentrantLock =new ReentrantLock();
//从某个字符开始
public static Character next = 'A';
public static void main(String[] args) {
// input
Character[] characters = {'A', 'B', 'C', 'D'};
Integer length = characters.length;
Condition[] conditions = new Condition[length];
for (int j = 0; j < length; j++) {
conditions[j] = reentrantLock.newCondition();
}
for (int j = 0; j < length; j++) {
new Thread(new Irunable(conditions[j], characters[j], characters[j + 1 >= length ? 0 : j + 1], conditions[j + 1 >= length ? 0 : j + 1])).start();
}
}
}
class Irunable implements Runnable {
public Condition currentCondition;
public Character c;
public Character nextC;
public Condition afterCondition;
public Irunable(Condition currentCondition, Character c, Character nextC, Condition afterCondition) {
this.currentCondition = currentCondition;
this.c = c;
this.nextC = nextC;
this.afterCondition = afterCondition;
}
@Override
public void run() {
while (true) {
try {
Main.reentrantLock.lock();
if (c != Main.next) {
currentCondition.await();
}
Thread.sleep(1000);
System.out.println(c);
Main.next = nextC;
afterCondition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Main.reentrantLock.unlock();
}
}
}
}
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于