使用AtomicInteger做计数器的一个例子:
package test.caipiao.log;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.ArrayList;
import java.util.Iterator;
public class CounterTest {
public static void main(String[] args) throws InterruptedException {
final Counter counter = new Counter();
// create 1000 threads
ArrayList<MyThread> threads = new ArrayList<MyThread>();
for (int x = 0; x < 1000; x++) {
threads.add(new MyThread(counter));
}
// start all of the threads
Iterator i1 = threads.iterator();
while (i1.hasNext()) {
MyThread mt = (MyThread) i1.next();
mt.start();
}
// wait for all the threads to finish
Iterator i2 = threads.iterator();
while (i2.hasNext()) {
MyThread mt = (MyThread) i2.next();
mt.join();
}
System.out.println("Count: " + counter.getCount());
}
}
// thread that increments the counter 100000 times.
class MyThread extends Thread {
Counter counter;
MyThread(Counter counter) {
this.counter = counter;
}
public void run() {
for (int x = 0; x < 100000; x++) {
counter.incrementCount();
}
}
}
// class that uses AtomicInteger for counter
class Counter {
private AtomicInteger count = new AtomicInteger(0);
public void incrementCount() {
count.incrementAndGet();
}
public int getCount() {
return count.get();
}
}
输出如下:
Count: 100000000
使用int做计数器的一个例子:
package test.caipiao.log;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.ArrayList;
import java.util.Iterator;
public class CounterTest2 {
public static void main(String[] args) throws InterruptedException {
final Counter2 counter = new Counter2();
// create 1000 threads
ArrayList<MyThread2> threads = new ArrayList<MyThread2>();
for (int x = 0; x < 1000; x++) {
threads.add(new MyThread2(counter));
}
// start all of the threads
Iterator i1 = threads.iterator();
while (i1.hasNext()) {
MyThread2 mt = (MyThread2) i1.next();
mt.start();
}
// wait for all the threads to finish
Iterator i2 = threads.iterator();
while (i2.hasNext()) {
MyThread2 mt = (MyThread2) i2.next();
mt.join();
}
System.out.println("Count: " + counter.getCount());
}
}
// thread that increments the counter 100000 times.
class MyThread2 extends Thread {
Counter2 counter;
MyThread2(Counter2 counter) {
this.counter = counter;
}
public void run() {
for (int x = 0; x < 100000; x++) {
counter.incrementCount();
}
}
}
// class that uses AtomicInteger for counter
class Counter2 {
private int count = 0;
public void incrementCount() {
count ++;
}
public int getCount() {
return count;
}
}
输出如下:
Count: 43034849
可以看到AtomicInteger例子输出结果是正确的,AtomicInteger 的incrementAndGet()是一个原子操作;
而int例子的输出结果是不正确的,int 的++不是一个原子操作。