

欢迎关注微信公众号:数据科学与艺术 作者WX:superhe199
线程安全指的是在多线程环境下,共享的资源能够被正确地访问和操作,不会出现数据不一致或者异常的情况。
为了确保线程安全,可以采取以下几种方式:
下面是一个简单的案例分析,展示如何确保线程安全:
public class Counter {
private int count = 0;
public synchronized void increment() {
count++;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
Counter counter = new Counter();
// 创建10个线程,每个线程对计数器进行1000次递增操作
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Thread thread = new Thread(() -> {
for (int j = 0; j < 1000; j++) {
counter.increment();
}
});
threads.add(thread);
thread.start();
}
// 等待所有线程执行完毕
for (Thread thread : threads) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Count: " + counter.getCount());
}
}Counter类中的increment()方法使用synchronized关键字保证了其原子性,确保多个线程对count变量的递增操作是线程安全的。最终输出的结果应该是10000,如果没有线程安全措施,可能会出现不确定的结果。