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();
}
}