两个线程交替打印0-100
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Main {
public static ReentrantLock lock = new ReentrantLock();
public static Condition odd = lock.newCondition();
public static Condition even = lock.newCondition();
public static char flag = 'e';
public static void main(String[] args) {
// 0
new Thread(() -> {
for (int i = 0; i <= 100; i += 2) {
lock.lock();
try {
while (flag != 'e') {
even.await();
}
System.out.println(Thread.currentThread().getName() + "打印 " + i);
flag = 'o';
odd.signal();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}).start();
// 1
new Thread(() -> {
for (int i = 1; i <= 100; i += 2) {
lock.lock();
try {
while (flag != 'o') {
odd.await();
}
System.out.println(Thread.currentThread().getName() + "打印 " + i);
flag = 'e';
even.signal();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} finally {
lock.unlock();
}
}
}).start();
}
}
标签:ReentrantLock,Java,lock,打印,static,100,public,Condition
From: https://www.cnblogs.com/DCFV/p/18391250