简单的并发测试例子

一个简单的并发测试的例子: 当线程数达到规定的数量,并发执行

package com.http.concurrent.test;

import java.util.concurrent.CyclicBarrier;

/**
 * 测试业务处理线程
 * @author lijunqing
 */
public abstract class WorkRun implements Runnable {

    private final CyclicBarrier barrier;

    public WorkRun(CyclicBarrier barrier) {
        this.barrier=barrier;
    }

    public void run() {
        try {
            System.out.println(Thread.currentThread().getId() + " thread is awaiting");
            barrier.await();
            process();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    protected abstract void process();

}

 

每个测试的都继承WorkRun;实现process借口,

 

测试例子:

public static void main(String[] args) {
        int count=1000;
        CyclicBarrier barrier=new CyclicBarrier(count);
        ExecutorService executorService=Executors.newFixedThreadPool(count);
        for(int i=0; i < count; i++) {
            executorService.execute(new LoginTest(barrier));
        }
        executorService.shutdown();
        long starttime=System.currentTimeMillis();
        while(!executorService.isTerminated()) {
            System.out.println("有没有关闭的");
        }
        long endtime=System.currentTimeMillis();
        System.out.println("starttime:" + starttime + "   endtime:" + endtime+"  所有线程完成用时:"+(endtime-starttime));
    }

 

结果:

  

8 thread is awaiting
10 thread is awaiting
9 thread is awaiting
12 thread is awaiting
11 thread is awaiting
********
37 thread is awaiting
39 thread is awaiting
1006 thread is awaiting
1007 thread is awaiting
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的
*********
有没有关闭的
有没有关闭的
1005 thread is awaiting
1003 thread is awaiting
1004 thread is awaiting
999 thread is awaiting
1001 thread is awaiting
*****
62 thread is awaiting
60 thread is awaiting
55 thread is awaiting
57 thread is awaiting
53 thread is awaiting
58 thread is awaiting
56 thread is awaiting
54 thread is awaiting
52 thread is awaiting
51 thread is awaiting
49 thread is awaiting
47 thread is awaiting
50 thread is awaiting
48 thread is awaiting
46 thread is awaiting
45 thread is awaiting
43 thread is awaiting
41 thread is awaiting
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的
有没有关闭的

有没有关闭的
有没有关闭的
有没有关闭的
*****
有没有关闭的
--start--working--43
*******
--start--working--168
--start--working--164
--start--working--166
--start--working--163
--start--working--165
--start--working--170
--start--working--172
--start--working--167
--start--working--178
--start--working--174
--start--working--180
--start--working--176
--start--working--169
--start--working--171
*******
--start--working--41
有没有关闭的
starttime:1394614101246   endtime:1394614101855  所有线程完成用时:609

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值