多线程并发测试类

同时并发的多线程测试类模板:

package test;

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

public class MultithreadTest {

	final int count = 250;
	static long beginTime;
	
	
	class MyThread implements Runnable {
		private CountDownLatch latch;
		private CyclicBarrier barrier;
		
		public MyThread(CountDownLatch latch,CyclicBarrier barrier){
			this.latch = latch;
			this.barrier = barrier;
		}
		@Override
		public void run() {
			try {
				barrier.await();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			} catch (BrokenBarrierException e1) {
				e1.printStackTrace();
			}
			new Thread(new TaskAlarm(latch)).start();
		}
	}
	
	class TaskAlarm implements Runnable{
		private CountDownLatch latch;
		
		public TaskAlarm(CountDownLatch latch){
			this.latch = latch;
		}
		
		@Override
		public void run() {
			for(int i=0;i<20;i++){
				//测试代码。。。。
			}
			System.out.println(Thread.currentThread().getName()+":,耗时:"+(System.currentTimeMillis()-beginTime)+"ms");
			latch.countDown();
		}
		
	}
	
	private void runThread() throws InterruptedException {
		CountDownLatch latch = new CountDownLatch(count);
		CyclicBarrier barrier = new CyclicBarrier(count);
		
		for (int i = 0; i < count; i++) {
			Thread tt = new Thread(new MyThread(latch,barrier));
			tt.start();
		}
		latch.await();
		System.out.println("消耗的总时间为:"+(System.currentTimeMillis()-beginTime));
		
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		beginTime = System.currentTimeMillis();
		try {
			new MultithreadTest().runThread();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}

 

你可能感兴趣的:(java编程)