CAS => 比较并交换,乐观锁
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class TestUnSafe {
private static AtomicInteger lock = new AtomicInteger(1);
private static int number = 0;
public static void lock() {
while (!lock.compareAndSet(1, 0)) { //获取锁失败一直死循环
}
}
public static void unlock() {
lock.compareAndSet(0, 1);
}
public static void test() {
lock();
for (int i = 0; i < 1000; i++) {
number++;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
unlock();
}
public static void main(String[] args) throws InterruptedException {
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; i++) {
threads.add(new Thread(() -> {
test();
}));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println(number);
}
}