// synchronized.java 示例代码
class Counter {
private int count = 0;
// 使用 synchronized 关键字来确保线程安全
public synchronized void increment() {
count++;
}
public synchronized int getCount() {
return count;
}
}
public class SynchronizedExample {
public static void main(String[] args) throws InterruptedException {
final Counter counter = new 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());
}
}
Counter 类中的 increment() 和 getCount() 方法使用了 synchronized 关键字。这确保了在多线程环境下,同一时间只有一个线程可以执行这些方法,从而避免了竞态条件(race condition)。SynchronizedExample 类中,我们创建了两个线程 t1 和 t2,它们同时对 Counter 对象的 count 变量进行递增操作。synchronized,我们可以确保即使在多线程环境下,count 的值也不会因为并发问题而出现错误的结果。希望这段代码和解释对你有帮助!
上一篇:java时间比较方法
下一篇:java %运算
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站