java CountDownLatch 模拟用户并发请求分析

哈哈 阅读:277 2021-03-31 21:33:31 评论:0

java.util.concurrent.CountDownLatch,一个同步辅助类,在完成一组正在其他线程中执行的操作之前,它允许一个或多个线程一直等待。

主要方法
 public CountDownLatch(int count);
 public void countDown();
 public void await() throws InterruptedException
 
构造方法参数指定了计数的次数
countDown方法,当前线程调用此方法,则计数减一
awaint方法,调用此方法会一直阻塞当前线程,直到计时器的值为0


示例代码:模拟多用户请求

package com.settlement.concurrent; 
 
import java.text.SimpleDateFormat; 
import java.util.Date; 
import java.util.concurrent.CountDownLatch; 
 
import com.settlement.commons.utils.HttpRequest; 
 
 
/** 
 * 模拟用户的并发请求,检测用户乐观锁的性能问题 
 *  
 * @author zzg 
 * @date 2017-02-10 
 */ 
public class ConcurrentTest { 
	final static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	public static void main(String[] args){ 
		CountDownLatch latch=new CountDownLatch(1);//模拟5人并发请求,用户钱包 
		 
		for(int i=0;i<5;i++){//模拟5个用户 
			AnalogUser analogUser = new AnalogUser("user"+i,"58899dcd-46b0-4b16-82df-bdfd0d953bfb","1","20.024",latch); 
			analogUser.start(); 
		} 
		latch.countDown();//计数器減一  所有线程释放 并发访问。 
		System.out.println("所有模拟请求结束  at "+sdf.format(new Date()));   
		 
	} 
	 
	static class AnalogUser extends Thread{ 
		String workerName;//模拟用户姓名 
		String openId; 
		String openType; 
		String amount; 
		CountDownLatch latch; 
		 
		public AnalogUser(String workerName, String openId, String openType, String amount, 
				CountDownLatch latch) { 
			super(); 
			this.workerName = workerName; 
			this.openId = openId; 
			this.openType = openType; 
			this.amount = amount; 
			this.latch = latch; 
		} 
 
		@Override 
		public void run() { 
			// TODO Auto-generated method stub 
			try {   
				latch.await(); //一直阻塞当前线程,直到计时器的值为0   
	        } catch (InterruptedException e) {   
	            e.printStackTrace();   
	        }  			 
			post();//发送post 请求   
	        
	        
			 
		}  
		 
		public void post(){ 
			String result = ""; 
			System.out.println("模拟用户: "+workerName+" 开始发送模拟请求  at "+sdf.format(new Date()));   
			result = HttpRequest.sendPost("http://localhost:8080/Settlement/wallet/walleroptimisticlock.action", "openId="+openId+"&openType="+openType+"&amount="+amount); 
			System.out.println("操作结果:"+result); 
			System.out.println("模拟用户: "+workerName+" 模拟请求结束  at "+sdf.format(new Date()));  
			 
		} 
		 
		 
		 
		 
		 
	} 
 
} 


声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

发表评论
搜索
KIKK导航

KIKK导航

排行榜
关注我们

一个IT知识分享的公众号