解决方案 »

  1.   

    问题解决,  在System.out.println(atomic.get());之前sleep一下,因为有些线程没有结束。
      

  2.   

    楼上正解。import java.util.concurrent.atomic.AtomicInteger;
    public class Volatiletest extends Thread {
     
        private static AtomicInteger atomic = new AtomicInteger(0);
     
        public void run() {
            atomic.getAndIncrement();
        }
     
        public static void main(String[] args) throws InterruptedException {
            Thread threads[] = new Thread[100];
            for (int i = 0; i < threads.length; i++) {
                threads[i] = new Volatiletest();
            }
            for (int i = 0; i < threads.length; i++) {
                threads[i].start();
            }
            Thread.sleep(1000);
            System.out.println(atomic.get());
        }
    }
      

  3.   

    这个是你代码里面自己new的线程和主线程没有顺序关系造成的数据脏读,import java.util.concurrent.atomic.AtomicInteger;
    public class Volatiletest extends Thread {
    private static AtomicInteger atomic = new AtomicInteger(0);
    private static int n = 0; public void run() {
    n++;
    atomic.getAndIncrement();
    if(n==100){
    System.out.println("第100次执行");
    }
    } public static void main(String[] args) throws InterruptedException {
    Thread threads[] = new Thread[100];
    for (int i = 0; i < threads.length; i++) {
    threads[i] = new Volatiletest();
    }
    for (int i = 0; i < threads.length; i++) {
    threads[i].start();
    }
    System.out.println(atomic.get());
    }
    },加个打印应该就能看出来了
      

  4.   


    sleep()多长时间?不是好的问题的解决办法。
    你要等待这100个线程都运行结束,则你要在  threads[i].start(); 之后 加上如下代码: try {
    threads[i].join();
    } catch (InterruptedException e) {}