java怎么给类变量线程安全
时间: 2024-02-05 07:12:17 浏览: 22
Java中可以使用synchronized关键字来保证类变量的线程安全,具体方法如下:
1. 在声明类变量时加上static关键字,将其定义为静态变量。
2. 在访问该变量的方法或代码块上添加synchronized关键字,以保证同一时间只有一个线程能够访问该变量。
例如,以下是一个线程安全的类变量的示例代码:
```
public class ThreadSafeDemo {
private static int count = 0;
public static synchronized void increment() {
count++;
}
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
increment();
}
});
Thread t2 = new Thread(() -> {
for (int i = 0; i < 1000; i++) {
increment();
}
});
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Count: " + count);
}
}
```
在这个示例中,increment() 方法上添加了 synchronized 关键字,以确保同一时间只有一个线程能够访问 count 变量。这样就可以保证 count 变量的线程安全性。