方式一:使用乐观锁
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);
}
}
本文探讨了两种并发控制策略——乐观锁和悲观锁,并通过Java代码实例展示了它们在多线程环境下的应用。乐观锁使用AtomicInteger实现无阻塞的并发更新,而悲观锁则采用synchronized关键字实现资源独占。对比分析了两种锁的性能和适用场景。
7823

被折叠的 条评论
为什么被折叠?



