为什么只能双线程安全呢,因为我们不能保证lock != 1的判断同一时间只有一个线程可以执行成功,这里可以用到unsafe类了,那么可能同时有多个线程都判断成功了 lock != 1的条件,从而全部进入循环。
而双线程肯定每次都是一个锁住了,一个解锁了
import java.util.ArrayList;
import java.util.List;
public class MyCAS {
private volatile static int lock = 1;
private volatile static int number = 0;
public static void lock() {
while (lock != 1) {
}
lock = 0;
}
public static void unlock() {
lock = 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 < 2; i++) {
threads.add(new Thread(() -> {
test();
}));
}
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
System.out.println(number);
}
}