标签:str public for levels ret star example app add
@Slf4j public class AddCompareDemo { private int a, b; public void add() { for (int i = 0; i < 10000; i++) { a++; b++; } } public void compare() { for (int i = 0; i < 10000; 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
这是同一个实例之间的行程安全问题。在方法上增加synchronize字段
@Slf4j public class AddCompareDemo { private int a, b; public synchronized void add() { for (int i = 0; i < 10000; i++) { a++; b++; } } public synchronized void compare() { for (int i = 0; i < 10000; 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()); } }
28988 不是100000.
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 }
标签:str public for levels ret star example app add
原文地址:https://www.cnblogs.com/Brake/p/12709500.html