java.util.concurrent

149 阅读1分钟

countDownLatch

一个或多个线程,需要等待一个或多个线程执行结束方可继续执行;

CountDownLatch countDownLatch = new CountDownLatch(10);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            int finalI = i;
            executorService.submit(()-> {
                try {
                    Thread.sleep(1000 * 12);
                } catch (InterruptedException e) {
                    throw new BusinessException(e.getMessage());
                }
                System.out.println("submit i =" + finalI);
            });
        }
        long l = System.currentTimeMillis();
        countDownLatch.await(10, TimeUnit.SECONDS);
        long duration  =( System.currentTimeMillis() - l )/ 1000;

        System.out.printf("duration=" + duration);

cyclicBarrier - 同步屏障

多个线程互相等待,知道达到一个同步点再一起执行;

semaphore - 信号量

像令牌桶一样,定好令牌桶的大小,需要tryAcquire()令牌

Exchanger

两个线程之间进行数据交换

public class ExchangerTest {

	private static final Exchanger<String> exgr = new Exchanger<String>();

	private static ExecutorService threadPool = Executors.newFixedThreadPool(2);

	public static void main(String[] args) {

		threadPool.execute(new Runnable() {
			@Override
			public void run() {
				try {
					String A = "银行流水A";// A录入银行流水数据
					exgr.exchange(A);
				} catch (InterruptedException e) {
				}
			}
		});

		threadPool.execute(new Runnable() {
			@Override
			public void run() {
				try {
					String B = "银行流水B";// B录入银行流水数据
					String A = exgr.exchange("B");
					System.out.println("A和B数据是否一致:" + A.equals(B) + ",A录入的是:"
							+ A + ",B录入是:" + B);
				} catch (InterruptedException e) {
				}
			}
		});

		threadPool.shutdown();

	}
}