java个人笔记之 i++ 线程不安全
程序员文章站
2022-07-14 10:41:07
...
public class Test {
static int i = 0;
public static void main(String[] args) {
test1();
//test2();
}
/**
* 不加锁
*/
public static void test1() {
for (int j = 0; j < 100; j++)
new Thread(() -> {try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i++);}).start();
}
/**
* 加锁
*/
public static void test2() {
for (int j = 0; j < 100; j++)
new Thread(() -> {try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized (Test.class) {System.out.println(i++);}}).start();
}
}
上一篇: 线程安全问题和解决方案
下一篇: throws与throw
推荐阅读