当前位置: 代码迷 >> 综合 >> 并发包 Semaphore,CountDownLatch,CyclicBarrier,Exchanger 实例:
  详细解决方案

并发包 Semaphore,CountDownLatch,CyclicBarrier,Exchanger 实例:

热度:70   发布时间:2023-11-23 10:15:22.0

  Semaphore,CountDownLatch,CyclicBarrier,Exchanger

import java.util.concurrent.*;/*** Created by HuaWeiBo on 2019/5/13.*/
public class Test {/*** 限制数量:多余的进行等待*/public static void semaphore() {ExecutorService executorService = Executors.newFixedThreadPool(5);Semaphore semaphore = new Semaphore(3);for (int i = 0; i < 10; i++) {int finalI = i;executorService.execute(new Thread(()->{try {// 只能运行三个线程semaphore.acquire();System.out.println("i:" + finalI);Thread.sleep(1000);semaphore.release();} catch (Exception e) {e.printStackTrace();}}));}executorService.shutdown();}/*** * @param count*/public static void testCountDownLatch() {System.out.println("准备-------");CountDownLatch countDownLatch = new CountDownLatch(10);for (int i = 0; i < 10; i++) {int finalI = i;new Thread(() -> {System.out.println("准备好了" + finalI);countDownLatch.countDown();}).start();}countDownLatch.await();System.out.println("开始泄洪");}/*** 信号枪:统一执行* @param count*/public static void cyclicBarrier(int count){CyclicBarrier cyclicBarrier = new CyclicBarrier(count);for (int i = 0; i < count; i++) {int finalI = i;new Thread(()->{try {System.out.println("---------进入等待:" + finalI);cyclicBarrier.await();System.out.println("开始奔跑:" + finalI);} catch (Exception e) {e.printStackTrace();}}).start();}}/*** 交换两个线程的数据*/public static void exchanger() {Exchanger<String> exchanger = new Exchanger<>();Thread a = new ExchangerThread(exchanger, "A", "a");Thread b = new ExchangerThread(exchanger, "B", "b");a.start();b.start();}public static void main(String[] args) throws Exception{//semaphore();//countDownLatch(100);//cyclicBarrier(100);exchanger();}public static class ExchangerThread extends Thread{Exchanger<String> exchanger;String name;String value;public ExchangerThread(Exchanger<String> exchanger, String name, String value) {this.exchanger = exchanger;this.value = value;this.name = name;}@Overridepublic void run() {try {String exchange = exchanger.exchange(value);System.out.println("name:" + name + ",value:" + exchange);} catch (InterruptedException e) {e.printStackTrace();}}}}

  相关解决方案