// Java并发编程示例:使用线程和同步
class Counter {
private int count = 0;
// 同步方法,确保同一时间只有一个线程可以访问该方法
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class ConcurrencyExample {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
// 创建多个线程来同时增加计数器的值
Thread thread1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
Thread thread2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
});
// 启动线程
thread1.start();
thread2.start();
// 等待线程执行完毕
thread1.join();
thread2.join();
// 输出最终的计数值
System.out.println("Final count: " + counter.getCount());
}
}
count
变量和一个 increment
方法。increment
方法是同步的(使用 synchronized
关键字),以确保在多线程环境中只有一个线程能够同时执行该方法,从而避免竞争条件。increment
方法 1000 次。通过 join
方法确保主线程等待子线程执行完毕后再输出最终的计数值。这个例子展示了如何使用同步机制来确保线程安全,并且正确地处理并发问题。
上一篇:java有序map
下一篇:java修饰符
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站