// Java 锁示例代码
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockExample {
private final Lock lock = new ReentrantLock();
private int count = 0;
public void increment() {
lock.lock(); // 获取锁
try {
count++;
} finally {
lock.unlock(); // 释放锁
}
}
public int getCount() {
return count;
}
public static void main(String[] args) throws InterruptedException {
LockExample example = new LockExample();
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
example.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Final count is: " + example.getCount());
}
}
synchronized关键字。它提供了更灵活的锁机制。try块中进行操作,确保即使发生异常也能通过finally块中的unlock()来释放锁。count进行递增操作,最终输出结果以验证锁的有效性。通过这种方式,可以确保多线程环境下的数据一致性。
上一篇:java 内部类
下一篇:java aes加密
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站