JAVA模拟高并发及多线程计数器

1、多线程高并发模拟实现可采用闭锁CountDownLatch,设置对应线程数的CountDownLatch,达到就绪条件后会多线程统一执行。这里只是单机模拟,因为线程采用抢占式执行方式,并不能完全模拟统一同时执行。

2、多线程计数器可采用乐观锁CAS实现类AtomicInteger等原子操作方法实现。

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ***************************************************************************
 * Description  :
 * Author       : cxx
 * Creation date: 2018/10/11.
 * Version      : 1.0
 * ***************************************************************************
 */
public class HighConcurrencyTest {
    public static void main(String[] args) {
        //这里的Runnable知识一个执行接口,后续放到Tread中作为统一执行实体,所以变量counter共享
        Runnable runnable = new Runnable() {
            private AtomicInteger counter = new AtomicInteger(0);

            @Override
            public void run() {
                //do something
                for (int i = 0; i < 100; i++) {
                    System.out.println(System.nanoTime() + " Thread:" + Thread.currentThread().getName() + "  Count:" + counter.incrementAndGet());
                }
            }
        };
        System.out.println("******** cost[ns]:" + startAllInOne(10, runnable));
    }

    public static long startAllInOne(int num, final Runnable runnable) {

        final CountDownLatch startGate = new CountDownLatch(1);
        final CountDownLatch endGate = new CountDownLatch(num);
        for (int i = 0; i < num; i++) {
            Thread t = new Thread() {
                @Override
                public void run() {
                    try {
                        startGate.await();  //等待开始门计数到0
                        try {
                            runnable.run();
                        } finally {
                            endGate.countDown(); //结束门计数减1,为最后所有线程结束后计时(或其它操作)做准备
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            };
            t.start();
        }
        long startTime = System.nanoTime();
        System.out.println(System.nanoTime() + " All thread are reading starting");
        startGate.countDown();  //先通过第一道门 然后线程统一进入开始执行
        try {
            //开启结束门,基本执行到此处countDownLatch已经为0,如果线程或线程执行耗时足够多这里才会有作用,所有执行结果会统一通过结束门
            endGate.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //结束门开启后这里的计时才会准确,因为所有线程都执行完毕
        return System.nanoTime() - startTime;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值