java atomic class study notes

Java SE5 introduced special atomic variable classes such as AtomicInteger, AtomicLong, and AtomicReference. These classes are atomic at the machine level. They are rarely used in conventional programming, but they are very useful in performance tuning.

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);
        	}
        }
	}

}

This program uses the atomic class AtomicInteger and eliminates the use of the synchronized keyword. It will not fail. Therefore, the Timer class is used to automatically terminate the program after 5 seconds.

The detailed principles of atomic classes can be found in the following blogs of other bigwigs:

Atomic class

Guess you like

Origin blog.csdn.net/weixin_43916777/article/details/104294165