// Java锁机制示例代码
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockExample {
private final Lock lock = new ReentrantLock(); // 创建一个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: " + example.getCount()); // 输出最终结果
}
}
synchronized
)类似的功能,但具有更丰富的功能和更好的性能。lock()
和 unlock()
方法来获取和释放锁。确保在任何情况下都释放锁,通常将 unlock()
放在 finally
块中。上一篇:java default的作用
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站