Home  >  Q&A  >  body text

java - volatile中i++的原子性问题

/**
 * @create on 17/3/27
 * @description
 */
public class Main {
    static volatile int i = 0;
    public static class PlusTask implements Runnable{
        @Override
        public void run(){
            for(int k=0; k<10000; k++)
                i++;
        }
    }

    public static void main(String[] args) throws InterruptedException{
        Thread[] threads = new Thread[10];
        for(int i=0;i<10;i++){
            threads[i] = new Thread(new PlusTask());
            threads[i].start();
        }

        for(int i=0;i<10;i++){
            threads[i].join();
        }

        System.out.println(i);
    }
}

请教各位大牛 为什么这里的输出总是小于10000? 已经调用了thread.join

怪我咯怪我咯2743 days ago681

reply all(3)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 10:54:11

    You may need this:

    public void run() {
                for (int k = 0; k < 10000; k++)
                    synchronized (Main.class) {
                        i++;
                    }
            }

    or define oneAtomicInteger

    • volatile only functions as a multi-thread cache consistency, and does not guarantee that only one thread will write variables at a certain time.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:54:11

    volitile does not guarantee atomicity

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:54:11

    The problem of multi-threaded operation of shared variables. Volitale cannot guarantee the atomicity of composite operations, which means that the latter thread cannot always see the modified value i of the previous thread. The solution is to lock or atomically operate

    reply
    0
  • Cancelreply