java 多線程(十四)

package com.thread.threadTest;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Exchanger
 * 例子:用於實現兩個人之間的數據交換,每個人在完成一定的事務後想於對方交換數據,
 * 第一個先拿出數據的人將一直等待第二個人拿着數據到來時,才能批次交換數據.
 */
public class ExchangerTest {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Exchanger exchanger = new Exchanger();
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String data = "xxx";
                    System.out.println("線程"+Thread.currentThread().getName()+"正在把數據"+data+ "換出去");
                    Thread.sleep((long) (Math.random()*10000));
                    String dataOne = (String) exchanger.exchange(data);
                    System.out.println("線程"+ Thread.currentThread().getName()+"換回的數據爲"+dataOne);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    String dataTwo = "AAA";
                    System.out.println("線程"+Thread.currentThread().getName()+"正在把數據"+dataTwo+ "換出去");
                    Thread.sleep((long) (Math.random()*10000));
                    String dataThree = (String) exchanger.exchange(dataTwo);
                    System.out.println("線程"+ Thread.currentThread().getName()+"換回的數據爲"+dataThree);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });


    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章