测试一、这里跑的可能都小于1000
public class Counter {
public static int count = 0;
public static void inc() {
//这里延迟1毫秒,使得结果明显
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
count++;
}
public static void main(String[] args) throws Exception {
//同时启动1000个线程,去进行i++计算,看看实际结果
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
Counter.inc();
}
}).start();
}
Thread.sleep(3000); //等3秒的目的就是让所有线程都跑完
//这里每次运行的值都有可能不同,可能为1000
System.out.println("运行结果:Counter.count=" + Counter.count);
}
}
运行结果:Counter.count=960
运行结果:Counter.count=990
测试二、这里跑的结果都等于1000
1 public class Counter {
2
3 public static int count = 0;
4
5 public synchronized static void inc() {
6 //这里延迟1毫秒,使得结果明显
7 try {
8 Thread.sleep(1);
9 } catch (InterruptedException e) {
10 }
11
12 count++;
13 }
14
15 public static void main(String[] args) throws Exception {
16
17 //同时启动1000个线程,去进行i++计算,看看实际结果
18
19 for (int i = 0; i < 1000; i++) {
20 new Thread(new Runnable() {
21 @Override
22 public void run() {
23 Counter.inc();
24 }
25 }).start();
26 }
27
28 Thread.sleep(3000); //等3秒的目的就是让所有线程都
29 //这里每次运行的值都有可能不同,可能为1000
30 System.out.println("运行结果:Counter.count=" + Counter.count);
31 }
32 }
运行结果:Counter.count=1000
运行结果:Counter.count=1000
测试三、这里跑的结果都等于1000
public class Counter {
public static AtomicInteger count = new AtomicInteger(0);
public static void inc() {
//这里延迟1毫秒,使得结果明显
try {
Thread.sleep(1);
} catch (InterruptedException e) {
}
count.getAndIncrement();
}
public static void main(String[] args) throws Exception {
//同时启动1000个线程,去进行i++计算,看看实际结果
for (int i = 0; i < 1000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
Counter.inc();
}
}).start();
}
Thread.sleep(3000); //等3秒的目的就是让所有线程都
//这里每次运行的值都有可能不同,可能为1000
System.out.println("运行结果:Counter.count=" + Counter.count);
}
}
运行结果:Counter.count=1000
运行结果:Counter.count=1000