// 使用 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();
// 创建两个线程,它们都会调用 increment 方法
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 is: " + counter.getCount());
}
}
synchronized 关键字用于确保多个线程在访问共享资源时不会发生冲突。它可以通过修饰方法或代码块来实现同步。increment 方法被 synchronized 修饰,这意味着在同一时间只能有一个线程可以执行该方法,从而避免了多个线程同时修改 count 变量导致的数据不一致问题。Thread.join() 方法用于等待线程执行完毕,确保主线程在两个子线程完成后才输出最终的结果。上一篇:java demo
下一篇:java map循环遍历
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站