// Java synchronized 示例代码
class Counter {
private int count = 0;
// 使用 synchronized 关键字修饰方法,确保同一时间只有一个线程可以访问此方法
public synchronized void increment() {
count++;
}
// 获取当前计数值
public int getCount() {
return count;
}
}
public class SynchronizedExample {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
// 创建两个线程同时对 counter 进行操作
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
// 输出最终的计数值
System.out.println("Final count: " + counter.getCount());
}
}
synchronized 关键字用于确保多个线程在同一时间只能有一个线程访问被修饰的方法或代码块。这可以防止并发问题,如数据竞争。increment 方法被 synchronized 修饰,因此当一个线程调用 increment 时,其他线程必须等待,直到当前线程完成对该方法的调用。count 的值在多线程环境下是正确的,不会出现竞态条件(race condition)。下一篇:java的类
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站