1)不安全的代码
package com.atguigu.test;
public class Test {
public static int count = 0;
public static void add() {
count++;
}
public static void sub() {
count--;
}
public static void main(String[] args) throws Exception {
new Thread(() -> {
for(int i = 0; i < 100000; i++){
add();
}
}).start();
new Thread(() -> {
for(int i = 0; i < 100000; i++){
sub();
}
}).start();
Thread.sleep(2000);
/**
* -2879
* 其实每次访问,发现打印的这个值都不太一样
*/
System.out.println(count);
}
}
2)并发安全的代码synchronized
package com.atguigu.test;
public class TestSync {
public static int count = 0;
public synchronized static void add() {
count++;
}
public synchronized static void sub() {
count--;
}
public static void main(String[] args) throws Exception {
new Thread(() -> {
for (int i = 0; i < 100000; i++) {
add();
}
}).start();
new Thread(() -> {
for (int i = 0; i < 100000; i++) {
sub();
}
}).start();
Thread.sleep(2000);
System.out.println(count); // 始终是0
}
}