学习java多线程,请同时参阅 Java多线程 信号量和屏障实现控制并发线程数量,主线程等待所有线程执行完毕1
学习java多线程,请同时参阅:java多线程CountDownLatch简单测试
Exchanger用于进行两个线程之间的数据交换。它提供一个同步点,在这个同步点,两个线程可以交换彼此的数据。
import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;public class ExchangeDemo {public static void main(String[] args) throws InterruptedException {ExecutorService threadPool= Executors.newFixedThreadPool(2);final Exchanger exchanger = new Exchanger();for(int i=0;i<6;i++){threadPool.execute(new Runnable(){@Overridepublic void run() {Object data = "---JavaThread-----exchanger-----" +Thread.currentThread().getName();try {System.out.println("------kai-------threadName-----" + Thread.currentThread().getName() + "==-data==" +"----" + data);data = exchanger.exchange(data);System.out.println("-------wan------threadName-----" + Thread.currentThread().getName() + "==-data==" +"----" + data);Thread.sleep(10000);System.out.println("-------------------------------------------------------------------------------" );} catch (InterruptedException e) {e.printStackTrace();}}});}System.out.println("---------------------开始交换数据---------------------" );}}