『阿男的技术漫谈时间』*09*谈一谈线程安全

本节课视频:

『阿男的技术漫谈时间』*09*谈一谈线程安全

本节课代码:

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author <a href="mailto:[email protected]">Weinan Li</a>
 */
public class Counter {
    private long val;
    private AtomicLong safeVal;

    public Counter(int initialVal) {
        val = initialVal;
        safeVal = new AtomicLong(initialVal);
    }

    public long unsafeGetAndIncrement() {
        // '++' operator is not thread safe
        return val++;
    }

    public long safeGetAndIncrement() {
        return safeVal.getAndIncrement();
    }

    public static void main(String[] args) throws Exception {
        Counter counter = new Counter(0);

        // Vector is thread safe.
        List<Long> store = new Vector<>();
        List<Long> store2 = new Vector<>();

        // Creating two threads to use counter.
        // We expect the counter values will always be different,
        // but actually there will be duplicated values.
        Thread threadA = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 1000000; i++) {
                    store.add(counter.unsafeGetAndIncrement());
                    store2.add(counter.safeGetAndIncrement());
                }
            }
        };

        Thread threadB = new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < 1000000; i++) {
                    store.add(counter.unsafeGetAndIncrement());
                    store2.add(counter.safeGetAndIncrement());
                }
            }
        };

        // Start two threads and wait for them to stop
        threadA.start();
        threadB.start();
        threadA.join();
        threadB.join();

        // set type won't store duplicated values
        Set purgedStore = new HashSet(store);
        Set purgedStore2 = new HashSet(store2);

        // output the result
        System.out.println("store size: " + store.size());
        System.out.println("purged store size: " + purgedStore.size());
        double rate = 100 * (1 - Double.valueOf(purgedStore.size()) / Double.valueOf(store.size()));
        System.out.printf("conflict rate: %.2f%%%n", rate);

        System.out.println("store2 size: " + store2.size());
        System.out.println("purged store2 size: " + purgedStore2.size());
        double rate2 = 100 * (1 - Double.valueOf(purgedStore2.size()) / Double.valueOf(store2.size()));
        System.out.printf("conflict rate: %.2f%%%n", rate2);
    }
}


程序输出:

store size: 2000000
purged store size: 1997011
conflict rate: 0.15%
store2 size: 2000000
purged store2 size: 2000000
conflict rate: 0.00%

你可能感兴趣的:(java,thread)