美文网首页
多线程测试一些写法示例

多线程测试一些写法示例

作者: 夜雨听风_b3d5 | 来源:发表于2020-02-13 16:57 被阅读0次

原子操作类AtomicInteger详解

转自:https://blog.csdn.net/fanrenxiang/article/details/80623884

这里运行了20个线程,每个线程对count变量进行1000此自增操作,如果上面这段代码能够正常并发的话,最后的结果应该是20000才对,但实际结果却发现每次运行的结果都不相同,都是一个小于20000的数字。这是为什么呢?

public class AtomicIntegerTest {

    private static final int THREADS_CONUT = 20;

    public static int count = 0;

    public static void increase() {

        count++;

    }

    public static void main(String[] args) {

        Thread[] threads = new Thread[THREADS_CONUT];

        for (int i = 0; i < THREADS_CONUT; i++) {

            threads[i] = new Thread(new Runnable() {

                @Override

                public void run() {

                    for (int i = 0; i < 1000; i++) {

                        increase();

                    }

                }

            });

            threads[i].start();

        }

        while (Thread.activeCount() > 1) {

            Thread.yield();

        }

        System.out.println(count);

    }

}

相关文章

网友评论

      本文标题:多线程测试一些写法示例

      本文链接:https://www.haomeiwen.com/subject/enrlfhtx.html