Exchangerの使用

1900 ワード

スレッドの間でデータを交換して、すべて到着してやっと交換して、ゲームの中で道具、金貨の交換
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<String> exchanger = new Exchanger<String>();
        service.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    String data1 = "zxx";
                    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) {

                    e.printStackTrace();
                }
            }
        });

        service.execute(new Runnable() {

            @Override
            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) {

                    e.printStackTrace();
                }
            }
        });
    }
}