
下面是一个简单的示例,它使用Java的synchronized关键字来保证数据的安全性,并使用线程池来提高程序的性能。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadSafeExample {
private int counter = 0;
public synchronized void increment() {
counter++;
}
public synchronized int getCounter() {
return counter;
}
public static void main(String[] args) {
ThreadSafeExample example = new ThreadSafeExample();
ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 1000; i++) {
executorService.submit(() -> {
example.increment();
});
}
executorService.shutdown();
while (!executorService.isTerminated()) {
// 等待所有任务完成
}
// 打印最终计数器的值
System.out.println("Final counter value: " + example.getCounter());
}
}