Java并发编程学习记录

原子性和易变性

2020-03-09  本文已影响0人  桐桑入梦

当一个域的值依赖于它之前的值时候,那么volatile也无法正常的工作。这里的i++就是这样,i++即 i = i + 1,这里的读取和写入是两个步骤。因此使用了volatile不能保证这个操作的正常运行。因为可能在读取之后另外一个线程再次读取了内容。

package concurrency;

import typeinfo.interfacea.A;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AtomicityTest implements Runnable{
    private int i = 0; //没有使用volatile修饰,存在可视性问题
    //这里缺少同步使得数值可以处在稳定的状态被读取
    public int getValue(){
        return i;
    }

    private synchronized void evenIncrement(){
        i++;
        i++;
    }
    @Override
    public void run(){
        while( true )
            evenIncrement();
    }

    public static void main(String[] args) {
        AtomicityTest at = new AtomicityTest();
        ExecutorService exec = Executors.newCachedThreadPool();
        exec.execute( at );
        exec.shutdown();

        while( true ) {
            int val = at.getValue();
            if( val % 2 != 0 ){
                System.out.println( val );
                System.exit(0 );
            }
        }
    }
}

上一篇下一篇

猜你喜欢

热点阅读