多线程中的乐观锁案例
问题:
使用乐观锁演示两个线程,一个打印1-100的奇数,一个打印1-100的偶数;要求:线程1打印5个之后,线程2开始打印,线程2打印5个之后,线程1再开始打印,以此循环。
使用乐观锁
public class Demo {
public static volatile boolean flag = false;
public static AtomicInteger num = new AtomicInteger();
public static void main(String[] args) {
new Thread(() -> {
while (num.get() < 100) {
if (flag) {
System.out.println(Thread.currentThread() + " " + num.getAndIncrement());
flag = false;
}
}
}, "奇数").start();
new Thread(() -> {
while (num.get() < 100) {
if (!flag) {
System.out.println(Thread.currentThread() + " " + num.getAndIncrement());
flag = true;
}
}
}, "偶数").start();
}
}```