When I use the volatile and AtomicInteger practice found that the output should have the output of the code disappeared, I hope someone can help me solve this problem
It should have output, but the output is gone,the code is here:
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();
}
}
}
This code is the same,code is here:
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();
}
}
}
The values in the for-loop is wrong. This:
for (int i = 10; i < 10; i++)
should be:
for (int i = 0; i < 10; i++)