AtomicInteger,一个提供原子操作的Integer的类。在Java语言中,++i和i++操作并不是线程安全的,在使用的时候,不可避免的会用到synchronized关键字。而AtomicInteger则通过一种线程安全的加减操作接口。
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @Description
* @Author
* @Date 2015-5-8 上午9:37:45
*/
public class ConcurrentAtomicTest {
private final static AtomicInteger atomicInteger=new AtomicInteger(1);
private static volatile int integer=1;;
/**
* @Description TODO
* @Return void
* @Throws
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// testAtomicInteger();
testInteger2();
}
public static void testAtomicInteger() {
String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
System.out.println("Start time : " + time);
int temp=atomicInteger.addAndGet(1);//add
atomicInteger.get();//get current
System.out.print(temp+",");
temp=atomicInteger.decrementAndGet();//Atomically decrements by one the current value.
System.out.print(temp+",");
temp=atomicInteger.getAndIncrement();//Atomically decrements by one the current value.
System.out.print(temp+",");
temp=atomicInteger.intValue();//Atomically decrements by one the current value.
System.out.print(temp+",");
atomicInteger.set(0);//Atomically decrements by one the current value.
temp=atomicInteger.get();
System.out.println(temp+",");
//result:2,1,1,2,0,
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5); // 创建5个执行线程
Runnable runnable = new Runnable() {
@Override
public void run() {
String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
atomicInteger.incrementAndGet();
System.out.println("Now Time : " + time+",integer:"+integer);
}
};
executor.scheduleWithFixedDelay(runnable, 2, 3, TimeUnit.SECONDS);
}
/**
* 测试int加1
* @Description TODO
* @Return void
* @Throws
*/
public static void testInteger2() {
String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
System.out.println("Start time : " + time);
integer++;
System.out.println("integer ++:"+integer);
integer--;
System.out.println("integer --:"+integer);
ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(5); // 创建5个执行线程
Runnable runnable = new Runnable() {
@Override
public void run() {
String time = new SimpleDateFormat("HH:mm:ss").format(new Date());
integer=integer+1;
System.out.println("Now Time : " + time+",testInteger2 Integer:"+atomicInteger.get());
}
};
executor.scheduleWithFixedDelay(runnable, 2, 3, TimeUnit.SECONDS);
}
// Start time : 10:27:16
// integer ++:2
// integer --:1
// Now Time : 10:27:18,testInteger2 Integer:1
// Now Time : 10:27:21,testInteger2 Integer:1
// Now Time : 10:27:24,testInteger2 Integer:1
// Now Time : 10:27:27,testInteger2 Integer:1
}