当我使用volatile和AtomicInteger实践时发现输出应该有代码消失的输出

When I use the volatile and AtomicInteger practice found that the output should have the output of the code disappears

我在使用volatile和AtomicInteger实践时发现输出应该有代码的输出消失了,希望有人能帮我解决这个问题

应该有输出,但是输出没有了,代码在这里:

package volatil;

import java.util.concurrent.atomic.AtomicInteger;

public class Count extends Thread {

  // private static volatile AtomicInteger key =new AtomicInteger(0);
  private static AtomicInteger key = new AtomicInteger(1);

  private static void add() {
    for (int i = 0; i < 1000; i++) {
      key.incrementAndGet();
    }
    System.out.println("now key is " + key);
  }

  @Override
  public void run() {
    add();
  }

  public static void main(String[] args) {
    Count[] counts = new Count[10];
    for (int i = 0; i < 10; i++) {
      counts[i] = new Count();
    }
    for (int i = 10; i < 10; i++) {
      counts[i].start();
    }
  }
}

这段代码是一样的,代码在这里:

package volatil;

public class Count extends Thread {

    private static volatile int key;

    private static void add() {
        for (int i = 0; i < 1000; i++) {
            key++;
        }
        System.out.println("now key is " + key);
    }

    @Override
    public void run() {
        add();
    }

    public static void main(String[] args) {
        Count[] counts = new Count[10];
        for (int i = 0; i < 10; i++) {
            counts[i] = new Count();
        }
        for (int i = 10; i < 10; i++) {
            counts[i].start();
        }
    }
}

for 循环中的值是错误的。这个:

for (int i = 10; i < 10; i++)

应该是:

for (int i = 0; i < 10; i++)