// Java 同步示例代码
class Counter {
private int count = 0;
// 使用 synchronized 关键字确保方法在同一时间只能被一个线程访问
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class SyncExample {
public static void main(String[] args) throws InterruptedException {
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();
// 输出最终的计数值,应该为 2000
System.out.println("Final count: " + counter.getCount());
}
}
count
变量和一个 increment
方法。increment
方法使用了 synchronized
关键字,确保同一时间只有一个线程可以执行该方法,从而避免了多个线程同时修改 count
变量导致的数据不一致问题。t1
和 t2
,每个线程都会调用 increment
方法 1000 次。通过 join
方法确保主线程等待两个子线程执行完毕后再输出最终的计数值。increment
方法是同步的,因此最终的计数值应该是 2000。这段代码展示了如何使用 synchronized
关键字来确保多线程环境下的数据一致性。
下一篇:java继承类怎么写
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站