程序的并发

 

import java.util.concurrent.atomic.AtomicLong;

public class Test {
    static long a;
    static AtomicLong atomic_b = new AtomicLong(0);
    static final long time = 10000000;

    public static void main(String[] args) {

        Thread thread1 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < time; i++) {
                    a++;
                    atomic_b.getAndIncrement();
                }
            }
        };
        
        thread1.start();

        Thread thread2 = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < time; i++) {
                    a--;
                    atomic_b.getAndDecrement();
                }
            }
        };
        
        thread2.start();        
        
        try {
            thread1.join();
            thread2.join();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        System.out.println("a = " + a);
        System.out.println("atomic_b = " + atomic_b);
    }
}

a = -1402376
atomic_b = 0

 

posted @ 2015-12-10 14:41  牧 天  阅读(124)  评论(0)    收藏  举报