// synchronized在Java中的作用
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,这意味着当一个线程调用该方法时,其他线程必须等待,直到当前线程完成对该方法的调用。count 变量的更新是线程安全的,避免了竞态条件(race condition),即多个线程同时修改同一个共享资源导致的数据不一致问题。下一篇:java判断数组是否为空的方法
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站