// Java 并发编程示例:使用线程和同步机制
class Counter {
private int count = 0;
// synchronized 关键字确保同一时间只有一个线程可以访问 increment 方法
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class ConcurrentExample {
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();
// 输出最终的计数值
System.out.println("Final count: " + counter.getCount());
}
}
Counter 类:
count 是一个共享变量,多个线程可能会同时对其进行修改。increment() 方法使用了 synchronized 关键字,确保同一时间只有一个线程可以执行该方法,从而避免了竞态条件(race condition)。ConcurrentExample 类:
t1 和 t2,每个线程都会调用 increment() 方法 1000 次。start() 方法启动线程,并使用 join() 方法等待线程执行完毕。通过这个例子,展示了如何在 Java 中使用线程和同步机制来处理并发问题。
上一篇:java 有序集合
下一篇:java hibernate
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站