Java之压测模拟代码

package com.jiazhen.oauth;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import com.jiazhen.oauth.service.CarService;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Oauth2Application.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class Oauth2ApplicationTests {

	private static final Integer MAX_THREADS = 200;
	
	private static final CountDownLatch odl = new CountDownLatch(MAX_THREADS);
	/**
	 * 第一个参数:参与线程的个数
	 * 第二个参数:最后一个到达线程要做的任务 可以省略
	 * CyclicBarrier 有两个构造函数 一个是带Runnable对象的 一个不带;
	 */
	private static final CyclicBarrier cyclicBarrier = new CyclicBarrier(MAX_THREADS,new Runnable() {
        
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " 完成最后任务");
        }
    });
	
	@Autowired
	private CarService carService;
	
	
	@Test
	public void testCountDownLatch() throws InterruptedException {
		System.out.println("============start==============");
		for (int i = 0; i < MAX_THREADS; i++) {
			Thread thread = new Thread(()->{
				try {
					odl.countDown();
					System.out.println("============starting==============");
					odl.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				carService.carColor();
			});
			thread.start();
		}
		Thread.sleep(5000);
		System.out.println("============end==============");
	}
	
	@Test
	public void testCyclicBarrier() {
		for (int i = 0; i < MAX_THREADS; i++) {
			Thread thread = new Thread(()->{
				try {
					System.out.println(Thread.currentThread().getName()+"======到达栅栏======");
					cyclicBarrier.await();
					System.out.println(Thread.currentThread().getName()+"======冲破栅栏======");
				} catch (Exception e) {
					e.printStackTrace();
				}
				carService.carColor(Thread.currentThread().getName());
			});
			thread.start();
		}
	}

}
posted @ 2021-06-28 17:27  鸿毛浮绿水  阅读(310)  评论(0)    收藏  举报