用於實現兩個人之間的數據交換,每個人在完成一定的事務後想與對方交換數據,第一個先拿出數據的人將一直等待第二個人拿著數據到來時,才能彼此交換數據。
package com.ljq.test.thread; import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ExchangerTest { public static void main(String[] args) { ExecutorService service = Executors.newCachedThreadPool(); final Exchanger exchanger = new Exchanger(); service.execute(new Runnable(){ public void run() { try { String data1 = "张三"; System.out.println("线程" + Thread.currentThread().getName() + "正在把数据'" + data1 +"'换出去"); Thread.sleep((long)(Math.random()*10000)); String data2 = (String)exchanger.exchange(data1); System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为'" + data2+"'"); }catch(Exception e){ } } }); service.execute(new Runnable(){ public void run() { try { String data1 = "李四"; System.out.println("线程" + Thread.currentThread().getName() + "正在把数据'" + data1 +"'换出去"); Thread.sleep((long)(Math.random()*10000)); String data2 = (String)exchanger.exchange(data1); System.out.println("线程" + Thread.currentThread().getName() + "换回的数据为'" + data2 + "'"); }catch(Exception e){ } } }); } }
回傳結果:
线程pool-1-thread-1正在把数据'张三'换出去 线程pool-1-thread-2正在把数据'李四'换出去 线程pool-1-thread-1换回的数据为'李四' 线程pool-1-thread-2换回的数据为'张三'
更多Java多執行緒程式設計之使用Exchanger資料交換實例相關文章請關注PHP中文網!