未使用原子类,测试代码
package constxiong.interview; /** * JDK 原子类测试 * @author ConstXiong * @date 2019-06-11 11:22:01 */ public class TestAtomic { private int count = 0; public int getAndIncrement() { return count++; } // private AtomicInteger count = new AtomicInteger(0); // // public int getAndIncrement() { // return count.getAndIncrement(); // } public static void main(String[] args) { final TestAtomic test = new TestAtomic(); for (int i = 0; i <3; i++) { new Thread(){ @Override public void run() { for (int j = 0; j <10; j++) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " 获取递增值:" + test.getAndIncrement()); } } }.start(); } } }
打印结果中,包含重复值
Thread-0 获取递增值:1
Thread-2 获取递增值:2
Thread-1 获取递增值:0
Thread-0 获取递增值:3
Thread-2 获取递增值:3
Thread-1 获取递增值:3
Thread-2 获取递增值:4
Thread-0 获取递增值:5
Thread-1 获取递增值:5
Thread-1 获取递增值:6
Thread-2 获取递增值:8
Thread-0 获取递增值:7
Thread-1 获取递增值:9
Thread-0 获取递增值:10
Thread-2 获取递增值:10
Thread-0 获取递增值:11
Thread-2 获取递增值:13
Thread-1 获取递增值:12
Thread-1 获取递增值:14
Thread-0 获取递增值:14
Thread-2 获取递增值:14
Thread-1 获取递增值:15
Thread-2 获取递增值:15
Thread-0 获取递增值:16
Thread-1 获取递增值:17
Thread-0 获取递增值:19
Thread-2 获取递增值:18
Thread-0 获取递增值:20
Thread-1 获取递增值:21
Thread-2 获取递增值:22
测试代码修改为原子类
package constxiong.interview; import java.util.concurrent.atomic.AtomicInteger; /** * JDK 原子类测试 * @author ConstXiong * @date 2019-06-11 11:22:01 */ public class TestAtomic { // private int count = 0; // // public int getAndIncrement() { // return count++; // } private AtomicInteger count = new AtomicInteger(0); public int getAndIncrement() { return count.getAndIncrement(); } public static void main(String[] args) { final TestAtomic test = new TestAtomic(); for (int i = 0; i <3; i++) { new Thread(){ @Override public void run() { for (int j = 0; j <10; j++) { try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " 获取递增值:" + test.getAndIncrement()); } } }.start(); } } }
打印结果中,不包含重复值
Thread-0 获取递增值:1
Thread-2 获取递增值:2
Thread-1 获取递增值:0
Thread-0 获取递增值:3
Thread-1 获取递增值:4
Thread-2 获取递增值:5
Thread-0 获取递增值:6
Thread-1 获取递增值:7
Thread-2 获取递增值:8
Thread-0 获取递增值:9
Thread-2 获取递增值:10
Thread-1 获取递增值:11
Thread-0 获取递增值:12
Thread-1 获取递增值:13
Thread-2 获取递增值:14
Thread-0 获取递增值:15
Thread-1 获取递增值:16
Thread-2 获取递增值:17
Thread-0 获取递增值:18
Thread-1 获取递增值:19
Thread-2 获取递增值:20
Thread-0 获取递增值:21
Thread-2 获取递增值:23
Thread-1 获取递增值:22
Thread-0 获取递增值:24
Thread-1 获取递增值:25
Thread-2 获取递增值:26
Thread-0 获取递增值:27
Thread-2 获取递增值:28
Thread-1 获取递增值:29
原文:https://www.cnblogs.com/ConstXiong/p/12020540.html