java多线程快速入门(十四)

使用atomicInteger解决了原子性问题(AtomicInteger保证每次只能一个线程操作count)

package com.cppdy;

import java.util.concurrent.atomic.AtomicInteger;

class MyThread10 extends Thread {

    //AtomicInteger每次只能一个线程操作count
    private static AtomicInteger count = new AtomicInteger(0);

    @Override
    public void run() {
        addCount();
    }

    public void addCount() {
        for (int i = 0; i < 1000; i++) {
            count.incrementAndGet();
        }
        System.err.println(getName()+"--"+count.get());
    }
}

public class ThreadDemo10 {

    public static void main(String[] args) throws Exception {
        MyThread10[] mtList = new MyThread10[10];
        for (int i = 0; i < mtList.length; i++) {
            mtList[i]=new MyThread10();
        }
        for (int i = 0; i < mtList.length; i++) {
            mtList[i].start();
        }
    }

}

原子性:保证10个线程都对count加了1000次,最终结果为10000

posted @ 2018-11-25 15:53  知识追求者  阅读(131)  评论(0编辑  收藏  举报