java并发测试代码

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RuntimeTest {

	public static void main(String[] args) {
		int count = 100000;//10万并发
		CyclicBarrier cyclicBarrier = new CyclicBarrier(count);
		ExecutorService executorService = Executors.newFixedThreadPool(count);
		long now = System.currentTimeMillis();
		for (int i = 0; i < count; i++)
			executorService.execute(new RuntimeTest().new Task(cyclicBarrier));

		executorService.shutdown();
		while (!executorService.isTerminated()) {
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		long end = System.currentTimeMillis();
		System.out.println("All is finished!---------"+(end-now));
	}

	public class Task implements Runnable {
		private CyclicBarrier cyclicBarrier;

		public Task(CyclicBarrier cyclicBarrier) {
			this.cyclicBarrier = cyclicBarrier;
		}

		@Override
		public void run() {
			try {
				// 等待所有任务准备就绪
				cyclicBarrier.await();
				// 测试内容
				System.out.println("hello word");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}

你可能感兴趣的:(java基础)