publicstaticvoidmain(String[] args)throws InterruptedException { final Counter counter = new Counter();
for (int i = 0; i < 1000; i++) { final Thread t = new Thread(() -> counter.incr()); t.start(); } Thread.sleep(3000); System.out.println("结果为:" + counter.getValue()); } }
结果是1000,但存在风险。
使用原子类
1 2 3 4 5 6 7 8 9 10 11
privatestaticclassCounter{ private AtomicInteger c = new AtomicInteger(0);
近期评论