CountDownLatch CyclicBarrier

 

package com.ls.java_concurrency.threadpoolexecutor;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadPoolExecutorDemo {
	final BlockingQueue<Runnable> queue = new SynchronousQueue<Runnable>();
	final ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 600, 30,
			TimeUnit.SECONDS, queue, Executors.defaultThreadFactory(),
			new ThreadPoolExecutor.AbortPolicy());
	final AtomicInteger completedTask = new AtomicInteger(0);
	final AtomicInteger rejectedTask = new AtomicInteger(0);
	static long beginTime;
	static int count = 1000;
	
	public void start() {
		CountDownLatch latch = new CountDownLatch(count);
		CyclicBarrier barrier = new CyclicBarrier(count);
		for(int i=0; i<count; i++)
			new Thread(new TestThread(latch, barrier)).start();
		
	}
	
	class TestThread implements Runnable {
		private CountDownLatch latch;
		private CyclicBarrier barrier;
		public TestThread(CountDownLatch latch, CyclicBarrier barrier) {
			this.latch = latch;
			this.barrier = barrier;
		}
		
		public void run() {
			try {
				barrier.await();
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				executor.execute(new Task(latch));
			}catch(RejectedExecutionException e) {
				latch.countDown();
				System.out.println("被拒绝的任务数为:用地" + rejectedTask.incrementAndGet());
			}
		}
	}
	
	class Task implements Runnable {
		private CountDownLatch latch;
		public Task(CountDownLatch latch) {
			this.latch = latch;
		}
		
		public void run() {
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println("执行的任务数为:" + completedTask.incrementAndGet());
			System.out.println("任务耗时:" + (System.currentTimeMillis() - beginTime) + " ms");
			latch.countDown();
		}
	}
	
	public static void main(String[] args) {
		beginTime = System.currentTimeMillis();
		ThreadPoolExecutorDemo demo = new ThreadPoolExecutorDemo();
		demo.start();
	}

}
 

 

 

你可能感兴趣的:(java,thread)