使用原子变量实现i++操作
package com.gwolf;
import java.util.concurrent.atomic.AtomicInteger;
public class TestAtomicDemo {
public static void main(String[] args) {
AtomicDemo atomicDemo = new AtomicDemo();
for(int i = 0;i<10;i++) {
new Thread(atomicDemo).start();
}
}
}
class AtomicDemo implements Runnable {
private AtomicInteger serialNumver = new AtomicInteger() ;
@Override
public void run() {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + ":" + getSerialNumver());
}
public int getSerialNumver() {
return serialNumver.getAndIncrement();
}
}