1 ImportJava.util.concurrent.Exchanger;2 ImportJava.util.concurrent.ExecutorService;3 Importjava.util.concurrent.Executors;4 5 /**6 * JAVA5 's exchanger sync Tool7 * For data exchange between two people, each person wants to exchange data with each other after completing a certain transaction ,8 * The first person to come up with the data will be waiting for the second person. When this data arrives, you can exchange data with each other .9 * @authorlitaiqingTen * One */ A Public classExchangertest { - Public Static voidMain (string[] args) { -Executorservice Service =Executors.newcachedthreadpool (); the FinalExchanger<string> Exchanger =NewExchanger<string>(); -Service.execute (NewRunnable () { - Public voidrun () { - Try { + -String data1 = "Zxx"; +SYSTEM.OUT.PRINTLN ("Thread" +Thread.CurrentThread (). GetName () A+ "Getting data" + data1 + "swap out"); atThread.Sleep ((Long) (Math.random () * 10000)); -String data2 =(String) Exchanger.exchange (data1); -SYSTEM.OUT.PRINTLN ("Thread" +Thread.CurrentThread (). GetName () -+ "Swap back data for" +data2); -}Catch(Exception e) { - in } - } to }); +Service.execute (NewRunnable () { - Public voidrun () { the Try { * $String data1 = "LHM";Panax NotoginsengSYSTEM.OUT.PRINTLN ("Thread" +Thread.CurrentThread (). GetName () -+ "Getting data" + data1 + "swap out"); theThread.Sleep ((Long) (Math.random () * 10000)); +String data2 =(String) Exchanger.exchange (data1); ASYSTEM.OUT.PRINTLN ("Thread" +Thread.CurrentThread (). GetName () the+ "Swap back data for" +data2); +}Catch(Exception e) { - $ } $ } - }); - } the}
17.JAVA5 's Exchanger Sync Tool