1. 程式人生 > >線程間使用Exchanger交換數據

線程間使用Exchanger交換數據

int ava ger 數據 util nal port [] dom

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 = "zxx"; System.out.println("a線程" + Thread.currentThread().getName() + "正在把數據" + data1 +"換出去"); Thread.sleep((long)(Math.random()*10000)); String data2 = (String)exchanger.exchange(data1); System.out.println("a線程" + Thread.currentThread().getName() + "換回的數據為" + data2); }catch(Exception e){ } } }); service.execute(new Runnable(){ public void run() { try { String data1 = "lhm"; 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){ } } }); } }

線程間使用Exchanger交換數據