public class VolatileTest {
static AtomicInteger data = new AtomicInteger();
public static void main(String[] args) {
int num = 10;
long time = System.currentTimeMillis();
ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
final CountDownLatch latch = new CountDownLatch(num);
for (int i = 0; i < 10; i++) {
cachedThreadPool.execute(new Runnable() {
public void run() {
try {
Thread.sleep(1000);
data.getAndIncrement();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(" End=== Thread:"+Thread.currentThread().getId());
latch.countDown();
}
});
}
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("总共耗时:" + (System.currentTimeMillis()-time)+" data="+data.get());
cachedThreadPool.shutdown();
}
}
输出结果:
End=== Thread:11
End=== Thread:15
End=== Thread:10
End=== Thread:9
End=== Thread:12
End=== Thread:14
End=== Thread:16
End=== Thread:18
End=== Thread:13
End=== Thread:17
总共耗时:1005 data=10