Java 实例级别的锁和类级别的锁
2021-02-16 06:18
标签:str public for levels ret star example app add 这是同一个实例之间的行程安全问题。在方法上增加synchronize字段 即可解决问题 28988 不是100000. Java 实例级别的锁和类级别的锁 标签:str public for levels ret star example app add 原文地址:https://www.cnblogs.com/Brake/p/12709500.html实例级别的锁
实例代码
@Slf4j
public class AddCompareDemo {
private int a, b;
public void add() {
for (int i = 0; i ) {
a++;
b++;
}
}
public void compare() {
for (int i = 0; i ) {
if (a b) {
log.info("a:{},b:{},{}", a, b, a > b);
}
}
}
}
执行
@SpringBootApplication
public class NewdemoApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(NewdemoApplication.class, args);
AddCompareDemo demo = new AddCompareDemo();
new Thread(() -> {
demo.add();
}).start();
new Thread(() -> {
demo.compare();
}).start();
}
}
执行结果
INFO 39336 --- [ Thread-30] com.example.newdemo.AddCompareDemo : a:5262,b:5894,true
解决
@Slf4j
public class AddCompareDemo {
private int a, b;
public synchronized void add() {
for (int i = 0; i ) {
a++;
b++;
}
}
public synchronized void compare() {
for (int i = 0; i ) {
if (a b) {
log.info("a:{},b:{},{}", a, b, a > b);
}
}
}
}
类级别
代码
public class ClassLevelSyncDemo {
private static int data;//类基本静态字段
public synchronized void count() {//此处默认是实例级别的锁
data++;
}
public static int getData() {
return data;
}
}
执行
@SpringBootApplication
@Slf4j
public class NewdemoApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(NewdemoApplication.class, args);
IntStream.rangeClosed(1, 100000).parallel().forEach(i ->
{
new ClassLevelSyncDemo().count();
});
log.info("" + ClassLevelSyncDemo.getData());
}
}
执行结果
解决方法
1 public class ClassLevelSyncDemo {
2
3 private static int data;//类基本静态字段
4 private static Object object = new Object();
5
6 public void count() {
7 synchronized (object) {
8 data++;
9 }
10 }
11
12 public static int getData() {
13 return data;
14 }
15 }