java 原子类学习笔记

java SE5引入了诸如AtomicInteger、AtomicLong、AtomicReference等特殊的原子性变量类。这些类是在机器级别上的原子性。在常规编程中它们很少派上用场,但在性能调优中,就大有用武之地。

public class AtomicIntegerTest implements Runnable{
    
    
    private AtomicInteger i=new AtomicInteger(0);
    public int getValue() {
    
    return i.get();}
    private void evenIncrement() {
    
    i.addAndGet(2);}
    public void run() {
    
    
    	while(true) {
    
    
    		evenIncrement();
    	}
    }
	public static void main(String[] args) {
    
    
		// TODO Auto-generated method stub
        new Timer().schedule(new TimerTask() {
    
    
        	public void run() {
    
    
        		System.err.println("absorting");
        		System.exit(0);
        	}
        },5000);
        AtomicIntegerTest ait=new AtomicIntegerTest();
        ExecutorService exec=Executors.newCachedThreadPool();
        exec.execute(ait);
        while(true) {
    
    
        	int val=ait.getValue();
        	if(val%2!=0) {
    
    
        		System.out.println(val);
        		System.exit(0);
        	}
        }
	}

}

这个程序使用原子类AtomicInteger而消除了synchronized关键字的使用是不会失败的,因此,Timer类用来在5秒后自动终止程序的运行。

详细的原子类的原理可以看以下其他大佬的博客:

原子类

猜你喜欢

转载自blog.csdn.net/weixin_43916777/article/details/104294165