两个线程,其中一个打印奇数,另一个打印偶数,打印的结果是按照顺序1~100,不使用锁。
import java.util.concurrent.atomic.AtomicInteger;
public class PrintOneToOneHundred {
private static int num = 1;
private static final AtomicInteger x = new AtomicInteger(0);
// 打印奇数
private static class PrintOdd extends Thread {
@Override
public void run() {
while (true) {
while (x.compareAndSet(0, 2)) {
int t = num++;
System.out.println(t);
x.compareAndSet(2, 1);
if (t == 99) return;
}
}
}
}
// 打印偶数
private static class PrintEven extends Thread {
@Override
public void run() {
while (true) {
while (x.compareAndSet(1, 3)) {
int t = num++;
System.out.println(t);
x.compareAndSet(3, 0);
if (t == 100) return;
}
}
}
}
public static void main(String[] args) {
new PrintOdd().start();
new PrintEven().start();
}
}
原文:https://www.cnblogs.com/SanjiApollo/p/13606062.html