乐趣区

java并发编程学习之casAtomicInteger二

示例

public class AtomicDemo {
    static int num1 = 0;
    static AtomicInteger num2 = new AtomicInteger(0);

    static class Thread1 extends Thread {
        @Override
        public void run() {
            try {sleep(100);
            } catch (InterruptedException e) {e.printStackTrace();
            }
            num1++;
        }
    }

    static class Thread2 extends Thread {
        @Override
        public void run() {
            try {sleep(100);
            } catch (InterruptedException e) {e.printStackTrace();
            }
            num2.incrementAndGet();}
    }

    public static void main(String[] args) throws InterruptedException {for (int i = 0; i < 1000; i++) {new Thread1().start();
            new Thread2().start();
        }
        Thread.sleep(2000);
        System.out.println("num1=" + num1);
        System.out.println("num2=" + num2.get());
    }
}

运行结果如下:

在多线程无锁的情况下,num1 总是小于等于 1000,而 num2 因为原子性的方法总是等于 1000。

退出移动版