public class Counter1 {
private static AtomicInteger count = new AtomicInteger(0);
public synchronized static void addCounter(){
count.incrementAndGet();
}
public static void main(String[] args) {
for (int i = 0; i < 10000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
addCounter();
}
}).start();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("计数器的值:" + count);
}
}
2、
public class Counter2 {
public static void main(String[] args) {
final ExecutorService pools = Executors.newFixedThreadPool(10);
final CountDownLatch begin = new CountDownLatch(1);
final CountDownLatch count = new CountDownLatch(10);
for (int i = 0; i < 10; i++) {
final int index = i;
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
begin.await();
Thread.sleep((long)Math.random() * 1000);
System.out.println("运动员" + index + "到达终点。");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
count.countDown();
}
}
};
pools.execute(runnable);
}
try {
System.out.println("开始。");
begin.countDown();
count.await();
System.out.println("结束。");
pools.shutdown();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}