兩個線程都等到交換函數才能完成交換數據操做,代碼以下:java
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(); } }