方式一:使用乐观锁
public class Test {
private static final AtomicInteger atomicInteger = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 100; i++) {
new Thread(atomicInteger::incrementAndGet).start();
}
Thread.sleep(500);
System.out.println(atomicInteger.get());
}
}
方式二:使用悲观锁
public class Test {
private static int num = 0;
public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 100; i++) {
new Thread(() -> {
synchronized (Test.class) {
num++;
}
}).start();
}
Thread.sleep(500);
System.out.println(num);
}
}