J.U.C工具包之Exchanger
什么是Exchanger:
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import java.util.concurrent.Exchanger; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ExchangerDemo { public static void main(String[] args) { ExecutorService executorService = Executors.newFixedThreadPool(2); Exchanger<String> exchanger = new Exchanger<String>(); executorService.execute(() -> { try { String fromAnothorThread = exchanger.exchange("This is :" + Thread.currentThread().getName() + " do u copy?"); System.out.println(Thread.currentThread().getName() + " got message :" + fromAnothorThread); } catch (InterruptedException e) { e.printStackTrace(); } }); executorService.execute(() -> { try { System.out.println("waiting 1 seconds to exchange"); Thread.sleep(1000); String fromAnothorThread = exchanger.exchange("This is :" + Thread.currentThread().getName() + " copy that!"); System.out.println(Thread.currentThread().getName() + " got message :" + fromAnothorThread); } catch (InterruptedException e) { e.printStackTrace(); } }); } } |
执行结果:
1 2 3 |
waiting 1 seconds to exchange pool-1-thread-2 got message :This is :pool-1-thread-1 do u copy? pool-1-thread-1 got message :This is :pool-1-thread-2 copy that! |
暂无评论