package com.lakala.mkst.service;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
static ReentrantLock lock = new ReentrantLock();
static Condition one = lock.newCondition();
static Condition two = lock.newCondition();
volatile static boolean printNum = true;
public static void main(String[] args) {
new Thread(() -> {
for (int a = 1; a < 27; a++) {
lock.lock();
try {
while (!printNum) {
one.await();
}
System.out.print(a);
printNum = false;
two.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}).start();
new Thread(() -> {
for (int a = 65; a <= 90; a++) {
lock.lock();
try {
while (printNum) {
two.await();
}
System.out.print((char) a);
printNum = true;
one.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}).start();
}
}
打印结果如下:1A2B3C4D5E6F7G8H9I10J11K12L13M14N15O16P17Q18R19S20T21U22V23W24X25Y26Z