两个线程都等到交换函数才能完成交换数据操作,代码如下:
package threadLock; import java.util.Random; import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ExchangerTest { public static void main(String[] args) { final Exchanger<String> ex = new Exchanger<String>(); ExecutorService service = Executors.newCachedThreadPool(); service.execute(new Runnable() { public void run() { String data1 = "5555"; System.out.println("线程" + Thread.currentThread().getName() + "正在把" + """ + data1 + ""交换出去" ); try { Thread.sleep(new Random().nextInt(1000)); String data2 = ex.exchange(data1); System.out.println("线程" + Thread.currentThread().getName() + "交换后的数据为"" + data2 + """); } catch (InterruptedException e) { e.printStackTrace(); } } }); service.execute(new Runnable() { @Override public void run() { String data1 = "gghhh"; System.out.println("线程" + Thread.currentThread().getName() + "正在把" + """ + data1 + ""交换出去" ); try { Thread.sleep(new Random().nextInt(1000)); String data2 = ex.exchange(data1); System.out.println("线程" + Thread.currentThread().getName() + "交换后的数据为"" + data2 + """); } catch (InterruptedException e) { e.printStackTrace(); } } }); service.shutdown(); } }